今天在测试 Math.random() 函数的时候,发现了一个奇怪的问题,最开始在第一个 for 循环中测试,结果输出全部为 0,以为是 random() 函数伪随机引起的,修改到第二个 for 循环中后发现一切正常。
但在继续测试的过程中(第 3 个 for 循环),发现原来问题是在强制转换时引起,只要不声明某一个 double 类型的值来储存 random() 方法得到的值而直接使用强制转换,一定会得到 0,这是为什么呢?
public class RandomLuckyAudience {
public static void main(String[] args) {
for(int i = 0; i < 10; i++){
int num = (int) Math.random() * 3;
System.err.println("num = " + num);
}
// num = 0
// num = 0
// num = 0
// num = 0
// num = 0
// num = 0
// num = 0
// num = 0
// num = 0
for( int i = 0; i < 10; i++){
double random = Math.random();
double luckyNum = random*3;
System.out.println("double = " + luckyNum + ", int = " + (int) luckyNum);
}
// double = 2.890974551493182, int = 2
// double = 1.5971466678951056, int = 1
// double = 1.4348488400741541, int = 1
// double = 2.4762102978586764, int = 2
// double = 0.9541699041578021, int = 0
// double = 2.10040834712865, int = 2
// double = 2.1036786411003243, int = 2
// double = 2.78565491928864, int = 2
// double = 1.380838157492293, int = 1
// double = 1.52299402873967, int = 1
for( int i = 0; i < 10; i++){
double random = Math.random();
double luckyNum = (int) random*3;
System.out.println("double = " + luckyNum + ", int = " + (int) luckyNum);
}
// double = 0.0, int = 0
// double = 0.0, int = 0
// double = 0.0, int = 0
// double = 0.0, int = 0
// double = 0.0, int = 0
// double = 0.0, int = 0
// double = 0.0, int = 0
// double = 0.0, int = 0
// double = 0.0, int = 0
// double = 0.0, int = 0
}
}
ringa_lee2017-04-17 14:55:52
運算子優先權的問題,
int num = (int) Math.random() * 3;
相當於
int num = ((int) Math.random()) * 3;
改成下面這個就好了
int num = (int) (Math.random() * 3);