您的位置:首页 > 编程语言 > Java开发

Java Math.round()

2013-09-18 10:31 218 查看

java Math.round()

下面的例子看起来太费解了,看到某本书上讲的很透彻。

Math.round()就是利用四舍五入法取整。
Math.ceil()向上取整,Math.floor()去除小数点后面的小数。
Math.round()的算法就是利用Math.floor(num+0.5)来实现这个算法的。
------------------------------------------------------------------------------------
public class MathTest {
public static void main(String[] args) {
System.out.println("小数点后第一位=5");
System.out.println("正数:Math.round(11.5)=" + Math.round(11.5));
System.out.println("负数:Math.round(-11.5)=" + Math.round(-11.5));
System.out.println();

System.out.println("小数点后第一位<5");
System.out.println("正数:Math.round(11.46)=" + Math.round(11.46));
System.out.println("负数:Math.round(-11.46)=" + Math.round(-11.46));
System.out.println();

System.out.println("小数点后第一位>5");
System.out.println("正数:Math.round(11.68)=" + Math.round(11.68));
System.out.println("负数:Math.round(-11.68)=" + Math.round(-11.68));
}
}

运行结果:

1、小数点后第一位=5
2、正数:Math.round(11.5)=12
3、负数:Math.round(-11.5)=-11
4、
5、小数点后第一位<5
6、正数:Math.round(11.46)=11
7、负数:Math.round(-11.46)=-11
8、
9、小数点后第一位>5
10、正数:Math.round(11.68)=12
11、负数:Math.round(-11.68)=-12

根据上面例子的运行结果,我们还可以按照如下方式总结,或许更加容易记忆:

1、参数的小数点后第一位<5,运算结果为参数整数部分。
2、参数的小数点后第一位>5,运算结果为参数整数部分绝对值+1,符号(即正负)不变。
3、参数的小数点后第一位=5,正数运算结果为整数部分+1,负数运算结果为整数部分。
终结:大于五全部加,等于五正数加,小于五全不加。―――――――――――――――――――――――――――――――――――――――――――――――――
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: