先通过以下实例来看看 Java Math floor、ceil、rint 及 round 各个方法的输出结果:
Test.java
import java.util.Scanner;public class Test {public static void main(String[] args) {Scanner sc = new Scanner(System.in);System.out.println("输入一个浮点数:");while(sc.hasNext()){double num = sc.nextDouble();System.out.println("Math.floor(" + num + ") = " + Math.floor(num));System.out.println("Math.ceil(" + num + ") = " + Math.ceil(num));System.out.println("Math.rint(" + num + ") = " + Math.rint(num));System.out.println("Math.round(" + num + ") = " + Math.round(num));}}}
执行以上程序测试输出:
$ javac Test.java $ java Test输入一个浮点数:2.2Math.floor(2.2) = 2.0Math.ceil(2.2) = 3.0Math.rint(2.2) = 2.0Math.round(2.2) = 2-2.2Math.floor(-2.2) = -3.0Math.ceil(-2.2) = -2.0Math.rint(-2.2) = -2.0Math.round(-2.2) = -2-2.5Math.floor(-2.5) = -3.0Math.ceil(-2.5) = -2.0Math.rint(-2.5) = -2.0Math.round(-2.5) = -22.5Math.floor(2.5) = 2.0Math.ceil(2.5) = 3.0Math.rint(2.5) = 2.0Math.round(2.5) = 32.7Math.floor(2.7) = 2.0Math.ceil(2.7) = 3.0Math.rint(2.7) = 3.0Math.round(2.7) = 3-2.7Math.floor(-2.7) = -3.0Math.ceil(-2.7) = -2.0Math.rint(-2.7) = -3.0Math.round(-2.7) = -3
解析输出
1、Math.floor() 向下取整 即小于这个数的最大的那个整数。
Math.floor(2.2) = 2.0; Math.floor(-2.2) = -3.0; Math.floor(2.5) = 2.0; Math.floor(-2.5) = -3.0; Math.floor(2.7) = 2.0; Math.floor(-2.7) = -3.0;
2、Math.ceil() 向上取整 即大于这个数的最小的那个整数。
Math.ceil(2.2) = 3.0; Math.ceil(-2.2) = -2.0; Math.ceil(2.5) = 3.0; Math.ceil(-2.5) = -2.0; Math.ceil(2.7) = 3.0; Math.ceil(-2.7) = -2.0;
3、Math.rint() 返回最接近该值的那个整数。
注意: 如果存在两个这样的整数 则返回其中的偶数。
4、Math.round() 四舍五入 但当参数为负数时不太好理解 直接上源码应该比较好理解 注意返回的是整型。
Math.round(x) = Math.floor(x + 0.5)
把以上代码带入以下实例测试:
Math.round(2.2) = 2; Math.round(-2.2) = -2; Math.round(2.5) = 3; Math.round(-2.5) = -2; Math.round(2.7) = 3; Math.round(-2.7) = -3
参考地址:https://blog.csdn.net/u012050154/article/details/52448260
尊贵的董事大人
英文标题不为空时 视为本栏投稿
需要关键字 描述 英文标题