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

use*_*666 7 c# arrays multiplication

我有一个任务,我需要找到数组中所有数字的乘积,我不知道如何做到这一点.

    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;
        }

    }
Run Code Online (Sandbox Code Playgroud)

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

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

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

我在foreach声明中做错了什么?提前致谢

编辑,省略我声明的值

    const int SIZE = 10;
    const int ZERO = 0;
    string userInput;
    int numberInputed;
    int prod = 1;
Run Code Online (Sandbox Code Playgroud)

它现在可以在输入所有十个值时工作,但是如果我为了打破循环而放置一个0,那么一切都等于0.如何防止0进入数组?

p.s*_*w.g 21

您可能初始化prod为0,这意味着无论您的数组中的数字是多少,prod都将保持为0.确保将其初始化为1以获得正确的结果:

int prod = 1;
foreach (int value in numbers)
{
    prod *= value;
}
Run Code Online (Sandbox Code Playgroud)

你也可以使用Linq的Aggregate扩展方法来做同样的事情:

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

int prod = numbers.Aggregate(1, (a, b) => a * b);
Run Code Online (Sandbox Code Playgroud)

更新

真正的问题(我之前没有注意到)是你的数组没有完全填充,如果你提前摆脱你的循环.因此,您未设置的任何数组条目仍初始化为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);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • +1.您总是设法提供多种方式.荣誉:) (2认同)