gpt4 book ai didi

c# - 如何将数组中的所有值相乘?

转载 作者:太空狗 更新时间:2023-10-29 19:52:24 24 4
gpt4 key购买 nike

我有一项作业需要找到数组中所有数字的乘积,但我不确定该怎么做。

    int[] numbers = new int[SIZE];

Console.WriteLine("Type in 10 numbers");
Console.WriteLine("To stop, type in 0");
for (int input = 0; input < SIZE; input++)
{
userInput = Console.ReadLine();
numberInputed = int.Parse(userInput);

if (numberInputed == ZERO)
{
numberInputed = ONE;
break;
}
else
{
numbers[input] = numberInputed;
}

}

这是我试图找到数组中所有数字的乘积的地方。

    foreach (int value in numbers)
{
prod *= value;
}

Console.WriteLine("The product of the values you entered is {0}", prod);

我在 foreach 语句中做错了什么?提前致谢

编辑,省略了我声明的值

    const int SIZE = 10;
const int ZERO = 0;
string userInput;
int numberInputed;
int prod = 1;

现在,当我输入所有十个值时它可以工作,但如果我输入 0 以打破循环,那么一切都等于 0。如何防止 0 被输入到数组中?

最佳答案

您可能会初始化 prod到 0,这意味着无论数组中有什么数字,prod将保持为 0。确保将其初始化为 1 以获得正确的结果:

int prod = 1;
foreach (int value in numbers)
{
prod *= value;
}

您还可以使用 Linq 的 Aggregate 做同样事情的扩展方法:

using System.Linq; // put with other using directives

int prod = numbers.Aggregate(1, (a, b) => a * b);

更新

真正的问题(我之前没有注意到)是如果您提前退出循环,您的数组将不会被完全填充。因此,您未设置的任何数组条目仍会初始化为 0。要解决此问题,请使用 List<int> 而不是 int[] :

using System.Collections.Generic; // put with other using directives

List<int> numbers = new List<int>(SIZE); // Capacity == SIZE

...

for (int input = 0; input < SIZE; input++)
{
...
if (numberInputed == ZERO)
{
break;
}
else
{
numbers.Add(numberInputed);
}
}

关于c# - 如何将数组中的所有值相乘?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20132884/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com