浅谈Math.round()和Math.random()
首先 一个是取整函数,一个是生成随机数函数
下面将用代码进行说明。
1 System.out.println(Math.round(0.4)); 2 System.out.println(Math.round(0.5)); 3 System.out.println(Math.round(0.6)); 4 System.out.println(Math.round(-0.4)); 5 System.out.println(Math.round(-0.5)); 6 System.out.println(Math.round(-0.6)); 7 /* 8 0 9 1 10 1 11 0 12 0 13 -1 14 */
所以正数是符合四舍五入规则
就正负数一起总结来说:都在其数值加0.5,然后向下取整
如-0.6----- -0.6+0.5=-0.1 取-1
随机数函数:
1 //region Math.round() 默认范围在[0,1)之间 2 //[m,n)=[4,5) n-m +m 3 double a = Math.random() * (5 - 4) + 4;//[4,5) 4 System.out.println(a); 5 //endregion 6 7 //region 如果需要4-5之间的 换一种方式: 8 //n+1-m,m 9 double aa = Math.random() * (5 + 1 - 4) + 4;//[4,6) 10 System.out.println(aa); 11 //endregion
1 double cc=9.9; 2 System.out.println((int) cc); 3 4 //9
浙公网安备 33010602011771号