2013-11-21 98 views
5

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

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进入数组?

+0

什么是与去错你的代码? –

回答

19

这是可能的,你初始化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); 
    } 
} 
+2

+1。你总是设法提供不止一种做事方式。荣誉:) –

+0

+1'fold'...我的意思是'Aggregate'。 –

+0

对不起,我使用声明的值更新了我的帖子。我尝试了你的方法,但我得到了一个“错误'System.Array'没有包含'Aggregate'的定义,也没有接收类型为'System'的第一个参数的扩展方法'Aggregate'。数组'可能被发现(你是否缺少使用指令或程序集引用?)“错误 – user2781666

1

的问题是,你没有保持跟踪有多少项目有在实际上被赋值的数组中。如果您使用零输入从循环中退出,则其余项目不变。由于默认情况下它们为零,因此您将在第二个循环中使用这些零值,并且在阵列中的某个位置有零时,总产品将变为零。有多少项的

跟踪有通过保持循环变量外循环:

int input = 0; 
while (input < SIZE) 
{ 
    userInput = Console.ReadLine(); 
    numberInputed = int.Parse(userInput); 
    if (numberInputed == ZERO) { 
     break; 
    } 
    numbers[input] = numberInputed; 
    input++; 
} 

现在你可以只使用实际分配的项目:

for (int i = 0; i < input; i++) { 
    prod *= numbers[i]; 
} 
相关问题