浅谈Math类rint方法与round区别
两者都是Math类提供用于取整一个浮点数的方法
区别一:返回值类型不同
rint:return double;
round:return int;
区别二:取整规则不同
round:为一般理解中的四舍五入,在x.5边界向上取整(eg:4.5->5)
rint:向下取整(eg:4.5->4.0)
注意:rint的特殊性
经测验rint的取整规则:(eg:X.5)
X为奇数:向上取整
X为偶数:向下取整
public static void main(String[] args) {
float i=0.5f;
double b=Math.rint(i);
for(;i<20;i++){
System.out.print("初始值为:"+i);
System.out.print(" round:"+Math.round(i));
System.out.println(" rint:"+Math.rint(i));
System.out.println("====================================");
}
}
运行结果为:
初始值为:0.5 round:1 rint:0.0
====================================
初始值为:1.5 round:2 rint:2.0
====================================
初始值为:2.5 round:3 rint:2.0
====================================
初始值为:3.5 round:4 rint:4.0
====================================
初始值为:4.5 round:5 rint:4.0
====================================
初始值为:5.5 round:6 rint:6.0
====================================
初始值为:6.5 round:7 rint:6.0
====================================
初始值为:7.5 round:8 rint:8.0
====================================
初始值为:8.5 round:9 rint:8.0
====================================
初始值为:9.5 round:10 rint:10.0
====================================
初始值为:10.5 round:11 rint:10.0
====================================
初始值为:11.5 round:12 rint:12.0
====================================
初始值为:12.5 round:13 rint:12.0
====================================
初始值为:13.5 round:14 rint:14.0
====================================
初始值为:14.5 round:15 rint:14.0
====================================
初始值为:15.5 round:16 rint:16.0
====================================
初始值为:16.5 round:17 rint:16.0
====================================
初始值为:17.5 round:18 rint:18.0
====================================
初始值为:18.5 round:19 rint:18.0
====================================
初始值为:19.5 round:20 rint:20.0
====================================
Process finished with exit code 0