我想獲得用戶輸入數字的平均值。我每次輸入數字輸出是始終在線Java中用戶平均輸入的數字
總和爲6個 多少個數字:4 平均:2.0
A,而需要循環,不幸的是,循環都是不允許的。我對Java很新,所以我的格式很瑣碎。我的代碼在哪裏是我的問題?
import java.util.Scanner;
public class LoopsEndingRemembering {
public static void main(String[] args) {
// program in this project exercises 36.1-36.5
// actually this is just one program that is split in many parts
Scanner reader = new Scanner(System.in);
int count = 0;
int sum = 0;
int endingVariable = -1;
int input = 0;
double average;
while (input >= endingVariable) {
System.out.println("Type numbers: ");
input = Integer.parseInt(reader.nextLine());
sum += count;
average = (double)sum/count;
count++;
if (input == endingVariable) {
System.out.println("Thank you and see you later!");
System.out.println("The sum is " + sum);
System.out.println("How many numbers: " + count);
System.out.println("Average: " + average);
break;
}
}
}
}
你使用你的調試器,並通過該程序?你爲什麼要把'count'加到'sum'而不是'input'?你從來沒有對「輸入」做任何事情!另外,在計算平均值而不是計算平均值2時,計算平均值*之前,計算平均值時,計數仍爲「1」。 – tnw 2014-11-20 17:06:17
[如何從給定值獲取平均值](http:// stackoverflow。com/questions/15516797/how-to-get-average-from-given-values) – jbutler483 2014-11-20 17:07:58