本文介绍了Java四舍五入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何将 numberGrade 的值向上调整,如果它是 89.5,它会变为 90.numberGrade 被视为双精度值,但将其设为 int 并不会对其进行四舍五入.

How can I rould the value of the numberGrade up so if it is 89.5 it goes to 90. numberGrade is taken in as a double but making it a int does not round it up or down.

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).

To round up, you can use Math.ceil(numberGrade). To round to the nearest integer, use Math.round(numberGrade).

参见:数学 班级

这篇关于Java四舍五入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 04:51