加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java Rounding Up

发布时间:2020-12-15 05:22:33 所属栏目:Java 来源:网络整理
导读:我如何将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 '
我如何将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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读