这是一个计算平均成绩的程序,我不知道我的代码有什么问题。它返回错误的答案。
编辑帖子以删除个人信息。 :
/**
* This program will calculate grade average of user input
* Date: 10/2/2015
*/
import java.util.Scanner;
public class GradeAVG {
public static void main(String[] args) {
avgGrade();
}
public static void avgGrade() {
Scanner keyboard = new Scanner (System.in);
double count = 0;
double avgGrade = 0 ;
double grade;
double total = 0;
System.out.println("Please input the grade");
grade = keyboard.nextDouble();
while(true){
System.out.println("Please input the grade");
grade= keyboard.nextDouble();
count = count + 1;
if (grade < 0) break;
total += grade;
avgGrade = total/count;
}
System.out.println ("Sum is " +total);
System.out.printf("The average of the %.0f grades are %.2f " ,count ,avgGrade);
}
}
输出:
Please input the grade
100
Please input the grade
50
Please input the grade
-9
Sum is 50.0
The average of the 2 grades are 50.00
总和应该是 150,平均数是 75。
最佳答案
问题是您在 while 循环开始之前从用户那里读取成绩,而之后您忽略了这个值。
您应该删除这两行,一切都会按预期进行。我在下面的代码片段中评论了这些行,以明确地向您展示问题。
public static void avgGrade() {
Scanner keyboard = new Scanner(System.in);
double count = 0;
double avgGrade = 0;
double grade;
double total = 0;
// System.out.println("Please input the grade");
// grade = keyboard.nextDouble();
while(true){
System.out.println("Please input the grade");
grade = keyboard.nextDouble();
count = count + 1;
if (grade < 0) break;
total += grade;
avgGrade = total/count;
}
System.out.println ("Sum is " +total);
System.out.printf("The average of the %.0f grades are %.2f " ,count ,avgGrade);
}
作为旁注,您应该始终尝试最小化每个变量的范围。此处,grade
变量仅在 while
循环中使用,因此您可以直接编写 double grade = keyboard.nextDouble();
并删除在方法的开头声明。
关于java - 平均成绩计算器不返回正确答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32904686/