2013-11-21 97 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]; 
} 
相關問題