Java Math rint()

也就是说,如果指定的值是5.8,那么最接近的数学整数值是6.0。而对于值5.4,最接近的数学整数值是5.0

rint() 方法的语法是

Math.rint(double value)

注意rint() 方法是一个静态方法。因此,我们可以直接使用类名Math来调用该方法。


rint() 参数

  • arg - 参数,返回其最接近数学整数的值

rint() 返回值

  • 返回 arg 最接近的、等于数学整数的值

示例:Java Math.rint()

class Main {
  public static void main(String[] args) {

    // Math.rint()
    // value greater than 5 after decimal
    System.out.println(Math.rint(1.878));  // 2.0

    // value less than 5 after decimal
    System.out.println(Math.rint(1.34));   // 1.0

    // value equal to 5 after decimal
    System.out.println(Math.rint(1.5));    // 2.0

    // value equal to 5 after decimal
    System.out.println(Math.rint(2.5));    // 2.0

  }
}

在上面的示例中,请注意这两个表达式,

// returns 2.0
Math.rint(1.5)

// returns 2.0
Math.rint(2.5)  

在这里,在这两种情况下,小数点后的值都等于5。但是,

  • 对于 1.5 - 该方法向上取整
  • 对于 2.5 - 该方法向下取整。

这是因为,在.5的情况下,该方法会四舍五入到最近的偶数。因此,在这两种情况下,该方法都四舍五入到2.0


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战