2012-02-20 71 views
-2

所以我試圖做一個控制檯程序,從用戶需要10個數字,並添加它們,然後平均數的總和。在do while循環中,程序應該繼續詢問下一個數字。C# - 數組問題。不讀取用戶輸入

{ 
     Console.WriteLine("Hey there! If you could go ahead and just give me like 10 numbers, that'd be great... And I'll tell you what, if you do, I'll add them up and average them all up for ya."); 

     // declare an array of strings 
     int[] aryNumbers; 
     int intSum = 0; 
     int intAverage = 0; 

     // initialize the array 
     aryNumbers = new int[10]; 

     aryNumbers[0] = int.Parse(Console.ReadLine()); 
     aryNumbers[1] = int.Parse(Console.ReadLine()); 
     aryNumbers[2] = int.Parse(Console.ReadLine()); 
     aryNumbers[3] = int.Parse(Console.ReadLine()); 
     aryNumbers[4] = int.Parse(Console.ReadLine()); 
     aryNumbers[5] = int.Parse(Console.ReadLine()); 
     aryNumbers[6] = int.Parse(Console.ReadLine()); 
     aryNumbers[7] = int.Parse(Console.ReadLine()); 
     aryNumbers[8] = int.Parse(Console.ReadLine()); 
     aryNumbers[9] = int.Parse(Console.ReadLine()); 

     do 
     { 
      Console.WriteLine("Okay, give me a number."); 
      aryNumbers[] = int.Parse(Console.ReadLine()); 

     } while (intSum != 0); 


     int intNumbers = aryNumbers.Length; 
     //for loop to average sum of array elements 
     for (int i = 0; i < intNumbers; i++) 
     { 
      intSum += aryNumbers[i]; 
     } 

     intAverage = intSum/intNumbers; 
     Console.WriteLine("You're average comes out to... " + intAverage); 

     Console.ReadKey(); 
    } 
} 

我真的不知道該怎麼辦,我很新的這

感謝

+6

這段代碼是否能夠正確編譯? do/while循環中的一些代碼看起來很可疑。 (此外,這是作業/教育?) – reuben 2012-02-20 04:54:05

+0

不,對不起。它沒有正確編譯。該錯誤在等號的do while循環內部顯示「Identifier expected」。是的,這是一個班級。我不一定在尋找答案,但只是一些幫助走上正確的道路。 – user1207424 2012-02-20 04:57:37

+1

這是一個很好的提示 - 您應該查看訪問數組中元素的語法。這樣做時,您必須提供明確的索引。 – reuben 2012-02-20 05:00:15

回答

1

這裏是我的代碼:

 using System.Linq; 

     ..... 

     Console.WriteLine("Hey there! If you could go ahead and just give me like 10 numbers, that'd be great... And I'll tell you what, if you do, I'll add them up and average them all up for ya."); 
     // declare the array 
     int[] aryNumbers = new int[10]; 

     for(int i =0; i<aryNumbers.Length;i++) 
     { 
      Console.WriteLine("Okay, give me a number."); 
      aryNumbers[i] = int.Parse(Console.ReadLine()); 
     } 


     int intAverage = (int)aryNumbers.Average(); 
     Console.WriteLine("You're average comes out to... " + intAverage); 

     Console.ReadKey();   
+6

我們儘量不要在這裏給人們提供答案,尤其是在作業時。據推測(希望?)OP想要學習如何自己做這個,而不僅僅是做這個任務。對於使用LINQ的情況,使用+ 1 + – 2012-02-20 05:03:14

+0

+1。然而,兩種風格批評也適用於海報的代碼示例:不需要明顯的註釋「聲明數組」,如果要使用匈牙利語,則使用標準的「rg」前綴作爲數組,而不是「元」。 – 2012-02-20 05:03:26

+1

如果這個問題是出於教育/家庭作業的目的,只是提供一個完整的解決方案可能不是很有幫助。 reuben 2012-02-20 05:03:42

3

有很多問題,你碼。我想你應該閱讀關於數組的一整章。 Here是MSDN的教程。

+0

非常感謝。不幸的是,我們沒有課程的教科書,如果我們沒有完美的筆記,我們搞砸了。再次感謝! – user1207424 2012-02-20 05:06:28

+0

@ user1207424:Google是我的課本! – atoMerz 2012-02-20 05:08:30