我需要创建一个程序来提示用户0-100之间的等级。当他们输入-1时,表示他们已经完成了输入成绩。我需要输入计数,平均值和标准偏差,但是由于某种原因,标准偏差的输出确实不正确。例如,当我两次输入50时,我的标准偏差是494.97。
import java.util.Scanner;
public class Grade {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a grade between 0-100?");
int grade = scanner.nextInt();
int[] grades = new int[100];
double sum = 0;
int i = 0;
while (grade != -1) {
grades[i] = grade;
i++;
sum += grade;
System.out.println("Enter a grade between 0 100?");
grade = scanner.nextInt();
}
double sumOfDifference = 0;
double average = sum / i;
for (int k = 0; k < grades.length; k++) {
double difference = (grades[k] - average) * (grades[k] - average);
sumOfDifference += difference;
}
double s = Math.sqrt(sumOfDifference / (i - 1));
System.out.printf("Count: %4d\n", i);
System.out.printf("Average: %.2f\n", average);
System.out.printf("Standard Deviation: %.2f\n", s);
}
}
答案 0 :(得分:0)
这里有
for (int k = 0; k < grades.length; k++) {
double difference = (grades[k] - average) * (grades[k] - average);
sumOfDifference += difference;
}
请注意,这会遍历所有等级的元素,包括尚未初始化的元素。可以仅通过检查用户输入的前i个元素来解决此问题。
for (int k = 0; k < i; k++) {
double difference = (grades[k] - average) * (grades[k] - average);
sumOfDifference += difference;
}