2012-12-02 37 views
2

有人可以幫助我。我很難修復我的代碼邏輯。這個程序應該計算用戶輸入的數字的平均值,假設數組的大小設置爲100,如果用戶輸入-99,程序將終止 我知道問題在while循環處理內陣列程序

Scanner input = new Scanner(System.in); 

    int[] num = new int[100]; 

    int ctr=0, sum=0, ave = 0; 

    while(num[ctr]!= -99) 
    { 
     System.out.print("Enter number: "); 
     num[ctr]= input.nextInt(); 

     sum += num[ctr]; 

     ctr++; 

    } 

    System.out.print("Numbers are "); 

    for(int x = 0; x<ctr; x++) 
    { 
     System.out.print(num[x] + " "); 
    } 

    ave = sum/(ctr-1); 
    System.out.println("Average is " + ave); 

    } 

} 
+2

您應該讀取'while'循環之外的第一個輸入。因爲當用戶輸入'-99'時,在循環內部增加'ctr',所以檢查的號碼是錯誤的。 – Maroun

+0

你能告訴我該怎麼做嗎?我真的不知道 –

回答

0

您應該讀取第一個輸入以外的while循環。因爲當用戶輸入-99時,在循環內部增加ctr,因此檢查將使用錯誤的編號。所以實際上你從來沒有檢查你想檢查的當前號碼。

int ctr=0, sum=0, ave = 0; 
System.out.print("Enter number: "); 
num[ctr]= input.nextInt(); 
while(num[ctr]!= -99) 
{ 
    sum += num[ctr]; 
    ctr++; 
    System.out.print("Enter number: "); 
    num[ctr]= input.nextInt(); 
} 

但是你需要處理,用戶只有輸入一個數字,在這種情況下,你被零除的情況下,和你得到了錯誤的平均水平。你也應該這樣做:代替

ave = sum/(ctr); 

ave = sum/(ctr-1); 

現在你會得到很好的效果。

+0

謝謝你的男人!它正在工作。我是一名新生IT學生btw。我是java的入門者。我有一個問題,是否類似於啓動輸入?謝謝 –

+0

我很高興它幫助:)我不明白你的意思,你能解釋你的問題嗎? – Maroun

0

您的while循環在數組填充時沒有終止條件。 (當輸入100個整數,並且ctr等於100.)

+0

謝謝你的男人。我已經嘗試模擬它,是的,你是對的 –

0

while循環的問題在於它從不查看剛進入的元素;它總是看着它後面的元素。