生成数学随机数(0 或 1)时出现问题
我想要一个随机数,0或1,然后它将返回到main(),如下面的代码所示。
import java.util.Scanner;
public class Exercise8Lab7 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numFlips = 0;
int heads = 0;
int tails = 0;
String answer;
System.out.print("Please Enter The Number Of Coin Tosses You Want: ");
numFlips = input.nextInt();
for(int x = 1;x <= numFlips; x++){
if(coinToss() == 1){
answer = "Tails";
tails++;
}
else{
answer = "Heads";
heads++;
}
System.out.print("\nCoin Toss " + x + ": " + answer);
}
System.out.println("\n\n====== Overall Results ======" +
"\nPercentage Of Heads: " + (heads/numFlips)*100 + "\nPercentage Of Tails: " + (tails/numFlips)*100);
}
public static int coinToss(){
double rAsFloat = 1 * (2 + Math.random( ) );
int r = (int)rAsFloat;
return r;
}
}
已经提出了许多使用该漏洞的解决方案。随机选项,我已经完成并完美地工作,但我想弄清楚为什么我不能让它工作。显然,我希望这个数字自己是一个int,所以我在生成随机数后将其转换为int。但无论我添加或乘以 Math.random() 什么,它总是要么是头,要么都是尾。从不混合。