Java 汇总

标签 java rounding

我怎样才能将 numberGrade 的值调高,如果它是 89.5,它会变成 90。numberGrade 被当作 double ,但将它设为 int 并不会向上或向下舍入。

public class GradeReporter
{
    // The limit is the inclusive lower limit for each letter
    // grade -- this means that 89.5 is an 'A' not a 'B'
    public static final double A_LIMIT = 90;
    public static final double B_LIMIT = 80;
    public static final double C_LIMIT = 70;
    public static final double D_LIMIT = 60;
    public static final double F_LIMIT = 60;

    /** Converts a numeric grade into a letter grade. Grades should be rounded to 
     *  nearest whole number
     *
     * @param a numeric grade in the range of 0 to 100
     * @returns a letter grade based on the numeric grade, possible grades are A, B, C, D and F.
     */
    public char letterGrade(double numberGrade)
    {
        int grade = int(numberGrade);
        if (grade >= A_LIMIT)
            letterGrade = 'A';
        else if (grade >= B_LIMIT)
            letterGrade = 'B';
        else if (grade >= C_LIMIT)
            letterGrade = 'C';
        else if (grade >= D_LIMIT)
            letterGrade = 'D';
        else if (grade < F_LIMIT)//4
            letterGrade = 'F';
        return letterGrade;
    }

最佳答案

向上舍入,您可以使用Math.ceil(numberGrade)。要舍入到最接近的整数,请使用 Math.round(numberGrade)

参见:the Math class

关于Java 汇总,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3705722/

相关文章:

java - 如何从类的字符串表示形式转换为类的实例?

Lua - 四舍五入到双倍

java - 如何在 Selenium Web 驱动程序中关闭 GWT 中的面板?

java - 将文档转换为字符串时出错

java - J2EE 使用 JMS 队列发送预定电子邮件

Java 使用 BigDecimal 除法

objective-c - 在 Objective-C 中将数字舍入到指定精度

c# - 如何防止 C# 端的 SQL 舍入小数 (18,4) 输出

python - round() 和 numpy.round() 之间的底层区别是什么?

java - 防止 jar 运行的多个实例