如何将数组中的值增加用户输入的百分比?在 C# 中

本文关键字:输入 百分比 用户 数组 增加 | 更新日期: 2023-09-27 18:36:01

所以我想在一个数组中存储几个值,然后我想将我存储的那些值修改为我也输入的百分比。这就是我到目前为止所拥有的,我只是不知道如何调用要修改的值我输入的百分比。

static void Main(string[] args)
    {
    double[] array = new double[5];
    Console.WriteLine("Enter 5 values.");
    for (int i = 0; i < 5; i++)
    {
        array[i] = Convert.ToDouble(Console.ReadLine());
    }
    double sum = 0;
    foreach (double d in array)
    {
        sum += d;
    }
    Console.WriteLine("The values you've entered and their index number.");
    Console.WriteLine("{0}{1,8}", "index", "value");
    for (int counter = 0; counter < 5; counter++)
        Console.WriteLine("{0,5}{1,8}", counter, array[counter]);
    Console.WriteLine("Enter percent increase ");
    double percent;
        percent = 1+1;
    Console.WriteLine("The percent is " + percent);
    Console.WriteLine("The new values increased by Percent are ");
    Console.ReadLine();
    }

如何将数组中的值增加用户输入的百分比?在 C# 中

您可以使用

Array.ConvertAll

double[] result = Array.ConvertAll(array, d => d + d * (percent/100));

您可以像做的那样询问数字:

double[] array = new double[5];    
for (int i = 0; i < 5; i++)
    array[i] = double.Parse(Console.ReadLine());

询问百分比:

double percent = double.Parse(Console.ReadLine()); // value between 0-100

并增加数组的每个值:

for (int i = 0; i < 5; i++)
    array[i] += array[i] * percent / 100.0; // Add the percent
您可以使用

简单的for循环。

var percentage = 1 + percent * 0.01;
for (int i = 0; i < 5; i++)
{
   array[i] = array[i] * percentage;
}

在数学上,将值增加 x% 相当于乘以 1+x/100.0 。当x为负时,递减的工作方式相同。

您现在需要做的就是迭代数组,并将每个数字乘以1+x/100.0