Java 如何输出概率值?
我试图输出赢得掷骰子游戏的概率 每次我尝试运行程序时,输出都是空的 代码如下:Java 如何输出概率值?,java,Java,我试图输出赢得掷骰子游戏的概率 每次我尝试运行程序时,输出都是空的 代码如下: import java.util.Random; public class CrapsGame { public static void main(String[] args) { int diceOne = 0; //declare the following variables as an integer int diceTwo = 0; int tot
import java.util.Random;
public class CrapsGame {
public static void main(String[] args) {
int diceOne = 0; //declare the following variables as an integer
int diceTwo = 0;
int tot = 0;
int tot2 = 0;
int point = 0;
int win = 0;
int loss = 0;
double prob;
Random randomNum = new Random(); // gives randomNum a random value
for (int counter = 1; counter <= 10000; counter++) { // the loop will run up to 10,000 times
diceOne = randomNum.nextInt(6) + 1; //gives a random value to the first dice
diceTwo = randomNum.nextInt(6) + 1; //gives a random value to the first dice
tot = diceOne + diceTwo; //calculates the first total
if (tot == 7 || tot == 11) //if sum equaled 7 or 11
{
win = win + 1;
} else if (tot == 2 || tot == 3 || tot == 12) //if sum equales to 2, 3, or 12
{
loss = loss + 1;
} else
{
point = tot;
do
{
diceOne = randomNum.nextInt(6) + 1; //do loop setting dice1 and 2 equaled to a random number
diceTwo = randomNum.nextInt(6) + 1;
tot2 = diceOne + diceTwo;
} while (tot2 != 7 || tot2 != point); //while sum2 is not equal to 7 or point
if (tot2 == 7) //if sum2 equal 7
{
loss = loss + 1;
} else if (tot2 == point) //else if sum2 equal to point
{
win = win + 1;
}
prob = win / (win + loss);
System.out.println(prob);
}
}
}
}
import java.util.Random;
公共类垃圾名称{
公共静态void main(字符串[]args){
int diceOne=0;//将以下变量声明为整数
int-two=0;
int-tot=0;
int-tot2=0;
int点=0;
int-win=0;
整数损失=0;
双探针;
Random randomNum=new Random();//给randomNum一个随机值
对于(int counter=1;counter Empty?我希望为0(如果概率确实为1,则为1)。在进行除法之前,将赢和/或输转换为double,以获得浮点除法,而不是整数除法:(double)win/(double)(win+loss)
。当(tot2!=7 | tot2!=point)时,这里有一个无限循环
当点
不是7点时,重新思考您的算法。完成时您该怎么办?您是否在输出上看到任何异常,如被零除、OutofMemoryError等?您可能需要调试代码、设置断点、检查变量值……谢谢大家的帮助,很抱歉,我离开了一会儿,因此无法立即执行y回答。我设法重新开始并重做了代码,它成功了!我仍然没有发现问题是空的?我希望为0(或者如果概率确实为1,则为1)。在进行除法之前,将赢和/或输转换为双精度,以获得浮点除法,而不是整数除法:(double)赢/(double)(赢+输)
。当(tot2!=7 | | tot2!=point)时,这里有一个无限循环当点
不是7点时,重新思考您的算法。完成时您该怎么办?您是否在输出上看到任何异常,如被零除、OutofMemoryError等?您可能需要调试代码、设置断点、检查变量值……谢谢大家的帮助,很抱歉,我离开了一会儿,因此无法立即执行y回答。我设法重新开始并重做代码,它成功了!我仍然没有发现问题