java - 平均成绩计算器不返回正确答案

标签 java sum average addition

这是一个计算平均成绩的程序,我不知道我的代码有什么问题。它返回错误的答案。

编辑帖子以删除个人信息。 :

/**
 * 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/

相关文章:

java - 使用 KeyStore -Java 存储自己制作的 key

java - 终止 Windows 服务时未调用 Stop 方法

Excel - 如何在组内创建累积和列?

Linux DB2 服务器表现出极端负载

java - Worklight 6.2 wlapp 部署给出错误 java 堆空间

Java Custom AbstractTableModel 在 Window/JTable 调整大小时之前不会更新 JTable 上的值

mysql - 带有连接的 SQL 聚合给出了错误的结果

mysql - 当 SKU 类似于 CP% DOMO SQL 时的 COST 总和

java - 从用户那里收集一个数组,打印最小的数字,最大的数字,计算平均值和中位数

c# - 将许多 TimeSpans 减少为更少的平均 TimeSpans 的干净方法?