【发布时间】:2015-09-26 01:44:02
【问题描述】:
我正在尝试制作一个在 1 和 0 之间选择随机数的程序。但是,当我运行该程序时,我一遍又一遍地得到相同的输出(20 次!)。我该如何解决这个问题?我听说Math.random() 比random() 更有偏见。
这是我的代码:
public class Startup {
public static void main(String[] args) {
double match = Math.random();
for(int i = 0; i <= 20; i++){
if(match < 0.05){
System.out.println("a");
}
else if(0.05 <= match && match <= 0.1){
System.out.println("b");
}
else if(0.1 < match && match <= 0.15){
System.out.println("c");
}
else if(0.15 < match && match <= 0.2){
System.out.println("d");
}
else if(0.2 < match && match <= 0.25){
System.out.println("e");
}
else if(0.25 < match && match <= 0.3){
System.out.println("f");
}
else if(0.3 < match && match <= 0.35){
System.out.println("g");
}
else if(0.35 < match && match <= 0.4){
System.out.println("h");
}
else if(0.35 < match && match <= 0.4){
System.out.println("i");
}
else if(0.4 < match && match <= 0.45){
System.out.println("j");
}
else if(0.45 < match && match <= 0.5){
System.out.println("k");
}
else if(0.5 < match && match <= 0.55){
System.out.println("l");
}
else if(0.55 < match && match <= 0.6){
System.out.println("m");
}
else if(0.6 < match && match <= 0.65){
System.out.println("n");
}
else if(0.65 < match && match <= 0.7){
System.out.println("o");
}
else if(0.7 < match && match <= 0.75){
System.out.println("p");
}
else if(0.75 < match && match <= 0.8){
System.out.println("q");
}
else if(0.8 < match && match <= 0.85){
System.out.println("r");
}
else if(0.85 < match && match <= 0.9){
System.out.println("s");
}
else if(0.9 < match && match <= 0.95){
System.out.println("t");
}
else if(0.95 < match && match <= 1){
System.out.println("u");
}
}
}
}
【问题讨论】:
-
但是,当我运行程序时,我一遍又一遍地得到相同的输出(20 次!)我不相信你。
-
其实我跑了,它返回1 21次,但这不是我问题的重点。
-
我猜你可以never be sure。我的猜测是fair dice roll。
-
双重匹配 = Math.random();只被调用一次,因为它在 for 循环之外。