Java GPA 计算器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18758151/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 10:48:41  来源:igfitidea点击:

Java GPA calculator

javacalculator

提问by user2673161

I have this code in my Main class. My issue is, when the GPA is calculated with total divided by classes. It does not give me the full number. EX if the total is 14 and the classes is 4 it is a 3.5, my code only gives me a 3.0. Does anyone know why, I greatly appreciate your help!

我的 Main 类中有此代码。我的问题是,当 GPA 是用总数除以班级来计算的。它没有给我完整的数字。EX 如果总数是 14,班级是 4,它是 3.5,我的代码只给我 3.0。有谁知道为什么,我非常感谢你的帮助!

Scanner input = new Scanner(System.in);
    System.out.print("How many classes did you have?: ");
    int classes = input.nextInt();
    String grades = "";
    int total = 0;
    int dec;



    for (int j = 0; j < classes; j++) {

        Scanner inputters = new Scanner(System.in);
        System.out.print("What is your Grade?: ");
        grades = inputters.nextLine();


        if (grades.equals("A")){
        dec = 4; 
        total += dec;

    } else if (grades.equals("B")){
        dec = 3;
        total += dec;

    } else if (grades.equals("C")){
        dec = 2;
        total += dec;

    } else if (grades.equals("D")){
        dec = 1;
        total += dec;

    } else if (grades.equals("F")){
        dec = 0;
        total += dec;

    }

    }


    double GPA = total / classes;
    System.out.println(GPA);

    DecimalFormat formatter = new DecimalFormat("0.##");
    System.out.println( formatter.format(GPA));

采纳答案by Erik Pragt

It's because you are dividing int's by int's, which will never result in a floating point number. Change the type of total / classes to double (or cast them), and the GPA will be the number you expect.

这是因为您将 int 除以 int,这永远不会产生浮点数。将 total / classes 的类型更改为 double(或强制转换),GPA 将是您期望的数字。

PS: Not that doubles are not really accurate, for example, 0.9 + 0.1 != 1.0. If you want to do 'proper' double calculations, use BigDecimal, and use the String constructors when using them.

PS:并不是说双打不是很准确,例如,0.9 + 0.1 != 1.0。如果要进行“正确的”双重计算,请使用 BigDecimal,并在使用它们时使用 String 构造函数。