有人可以幫助我。我很難修復我的代碼邏輯。這個程序應該計算用戶輸入的數字的平均值,假設數組的大小設置爲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);
}
}
您應該讀取'while'循環之外的第一個輸入。因爲當用戶輸入'-99'時,在循環內部增加'ctr',所以檢查的號碼是錯誤的。 – Maroun
你能告訴我該怎麼做嗎?我真的不知道 –