首页 > 解决方案 > 你如何在java中四舍五入一个双用户输入值?

问题描述

我是一个正在制作简单评分系统的学生,我正在努力解决如何做到这一点

当我输入一个特定的数字时,它会绕过我的 else-if 语句,这些数字是 98、67、98、80 和 81,我不知道为什么会这样

这是我的代码:

public static void main(String[]args) {

    double grade=0,tgrade=0,r;
    int gcount=0;


    for (int i = 0; i<5;i++) {

        grade   = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter the grades "));
        tgrade = tgrade+grade;
        gcount++;
        System.out.println(gcount+". "+"grade: "+grade );

    }
    DecimalFormat c = new DecimalFormat("##.##");
    
    tgrade = tgrade/500*100;
    r = new Double(c.format(tgrade)).doubleValue();
    
    System.out.print("Total Grade: "+(tgrade)+"\n");
    if      (r >= 95 && r <=100) {
        JOptionPane.showMessageDialog(null, "High Honor");
    }else if (r >= 90 && r <= 94){
        JOptionPane.showMessageDialog(null, "Honor");
    }else if (r >=85 && r <= 89) {
        JOptionPane.showMessageDialog(null, "Good");
    }else if (r>=80 && r<=84)   {
        JOptionPane.showMessageDialog(null, "Satisfactory");
    }else if (r>=75 && r<= 79) {
        JOptionPane.showMessageDialog(null, "Low pass, but certifying");
    }else {
        JOptionPane.showMessageDialog(null, "Low Failure");
    }
}

}

标签: javadoubledecimal

解决方案


你的变量 r 是双倍的。

例如 :

You have these numbers : 98, 67, 98, 80 and 81
The average is : 424/5 = 84.8

此值 84.8 不符合您编写的条件:

if (r >=85 && r <= 89)
if (r>=80 && r<=84)

因此它要出去了。

您可以使用以下选项。

第一个选项:不要使用以下范围:

if (r >= 95) {
    JOptionPane.showMessageDialog(null, "High Honor");
}else if (r >= 90){
    JOptionPane.showMessageDialog(null, "Honor");
}else if (r >= 85){
    JOptionPane.showMessageDialog(null, "Good");
}else if (r >= 80){
    JOptionPane.showMessageDialog(null, "Satisfactory");
}else if (r >= 75){
    JOptionPane.showMessageDialog(null, "Low pass, but certifying");
}else {
    JOptionPane.showMessageDialog(null, "Low Failure");
}

第二个选项:如果您使用范围,则将条件框起来,如下所示:

if (r >= 95 && r <= 100) {
    JOptionPane.showMessageDialog(null, "High Honor");
}else if (r >= 90 && r < 95){
    JOptionPane.showMessageDialog(null, "Honor");
}else if (r >= 85 && r < 90) {
    JOptionPane.showMessageDialog(null, "Good");
}else if (r >= 80 && r < 85) {
    JOptionPane.showMessageDialog(null, "Satisfactory");
}else if (r >= 75 && r < 80) {
    JOptionPane.showMessageDialog(null, "Low pass, but certifying");
}else {
    JOptionPane.showMessageDialog(null, "Low Failure");
}

第三个选项:如果您需要四舍五入,那么您可以使用 Math.abs 从double r

例子 :

Math.abs(r)

推荐阅读