我正在練習(xí)一個問題:鍵入多個數(shù)字并在鍵入 0 時(shí)停止。打印出您鍵入的數(shù)字的最大值、最小值和平均值。以下是我的代碼,我被困在平均值的計(jì)算中。例如:當(dāng)我輸入:2 5 7 -1 0 結(jié)果是:Type some numbers, and type 0 to end the calculattion: 2 5 7 -1 0The numbers you type are: 2 5 7 -1 Sum is: 13There are 4 numbersThe Max number is : 7The minimum number is : -1Average is : 3.0但是,平均值應(yīng)為 3.25。我已經(jīng)將變量 avg 設(shè)為 double 類型,為什么我的輸出仍然是 3.0 而不是 3.25?謝謝?。ublic class Max_Min_Avg {public static void main(String[] args) { System.out.println("Type some numbers, and type 0 to end the calculattion: "); Scanner scanner = new Scanner(System.in); int numbs = scanner.nextInt(); int count =0; int sum =0; int max = 0; int min=0; System.out.println("The numbers you type are: "); while(numbs!=0) { System.out.print(numbs + " "); sum += numbs; count ++; numbs = scanner.nextInt(); if(numbs>max) { max = numbs; } if(numbs<min) { min = numbs; } } while(numbs ==0) { break; } System.out.println(); double avg = (sum/count); System.out.println("Sum is: "+ sum); System.out.println("There are "+ count + " numbers"); System.out.println("The Max number is : " + max ); System.out.println("The minimum number is : " + min); System.out.println("Average is : " + avg);}
1 回答

慕田峪7331174
TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超13個贊
這是整數(shù)除法的問題。sum/count計(jì)算為 int 因?yàn)閟um并且count是類型int。您可以通過隱式強(qiáng)制轉(zhuǎn)換來解決這個問題 。
嘗試 :-
double avg = sum*1.0/count; // implicit casting.
輸出 :-
Type some numbers, and type 0 to end the calculattion:
2 5 7 -1 0
The numbers you type are:
2 5 7 -1
Sum is: 13
There are 4 numbers
The Max number is : 7
The minimum number is : -1
Average is : 3.25
添加回答
舉報(bào)
0/150
提交
取消