黑马程序员技术交流社区
标题: Math.round(11.5)等於多少? Math.round(-11.5)等於多少? [打印本页]
作者: 风云1989 时间: 2016-12-3 14:30
标题: Math.round(11.5)等於多少? Math.round(-11.5)等於多少?
本帖最后由 风云1989 于 2016-12-3 14:38 编辑
Math.round(11.5)等於多少? Math.round(-11.5)等於多少?
一.首先,我们先认识Math类
Math类是数学操作类,提供了一系列的数学操作方法,
在Math类中提供的一切方法都是静态方法,所以类名直接调用即可
a.常用的操作方法有
1. 求平方根 Math.sqrt(9.0);
2.求最值 Math.max(10,30); Math.min(10,30);
3.求次方(2的3次方) Math.pow(2,3);
4.四舍五入(舍去小数点后面的数) Math.round(33.6);
5.随机数 Math.rondom();
二:部分源码分析
public final class Math { //此类不能被继承
private Math() {} //私有构造器
public static final double E = 2.7182818284590452354;
public static final double PI = 3.14159265358979323846;
}
关于round方法的源码:
public static int round(float a) {
int intBits = Float.floatToRawIntBits(a);
int biasedExp = (intBits & FloatConsts.EXP_BIT_MASK)
>> (FloatConsts.SIGNIFICAND_WIDTH - 1);
int shift = (FloatConsts.SIGNIFICAND_WIDTH - 2
+ FloatConsts.EXP_BIAS) - biasedExp;
if ((shift & -32) == 0) { // shift >= 0 && shift < 32
int r = ((intBits & FloatConsts.SIGNIF_BIT_MASK)
| (FloatConsts.SIGNIF_BIT_MASK + 1));
if (intBits < 0) {
r = -r;
}
return ((r >> shift) + 1) >> 1;
} else {
return (int) a;
}
}
//{:8_525:} 源码根据各种位运算,很复杂,总之记住 当Math.round(a); 传入的是负数,就要遵循 5舍6入的法则;
所以:Math.round(11.5) =12;
Math.round(-11.5)= -11;
作者: 风云1989 时间: 2016-12-3 21:28
dothings 发表于 2016-12-3 21:25 
研究这个问题首先要搞清楚 四舍五入的 舍和入 是什么意思;
在数学上就是 舍,减少这个值的小数部分,让这 ...
谢谢!
作者: cumtwjc 时间: 2016-12-3 22:49
太难了 看不懂
作者: 风云1989 时间: 2016-12-3 23:35
哪里看不懂?我讲你听
作者: zyq 时间: 2016-12-4 12:48
cumtwjc 发表于 2016-12-3 22:49 
太难了 看不懂
知道意思就行了,源代码确实难理解,功力不够
作者: 风云1989 时间: 2016-12-4 20:04
又凌乱了 。。。。。
-11.500000001 怎么就-12了
作者: 风云1989 时间: 2016-12-4 20:06
更新错,小于或者等于5舍去 大于5就进1
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) |
黑马程序员IT技术论坛 X3.2 |