黑马程序员技术交流社区
标题:
此事真是及其蹊跷,关于Math.round
[打印本页]
作者:
Yov正
时间:
2014-5-17 01:25
标题:
此事真是及其蹊跷,关于Math.round
本帖最后由 Yov正 于 2014-5-18 13:01 编辑
:L jdk中的解释:static int round(float a) 返回最接近参数的 int 。
static long round(double a) 返回最接近参数的 long。
public class Main {
public static void main(String[] args) {
Random r = new Random();
for (int i = 0; i < 20; i++) {
int x = r.nextInt(5000);
System.out.println(x+" =========== "+Math.round( x / 1000));
}
}
}
复制代码
结果明明是全舍去啊
3970 =========== 3
245 =========== 0
2419 =========== 2
4910 =========== 4
2470 =========== 2
3912 =========== 3
1598 =========== 1
3698 =========== 3
复制代码
作者:
钟成军
时间:
2014-5-17 02:55
x是int型,x/1000的结果向上转型为float型,调用static int round(float a) 方法,所以结果为整数啊,没有错啊
作者:
焚雨成灰
时间:
2014-5-17 12:11
本帖最后由 焚雨成灰 于 2014-5-17 12:13 编辑
x/1000 算出来的是int型,后来自动向上转成double
拿3970来说,整个过程是这样的
3970 / 1000 ---> 3 因为这是int型计算3 ---> 转成double型 3.0 Math.round(double d)
结果是3
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2