骰子概率计算程序异常求助:输出概率始终为0问题排查
嘿,我帮你找出代码里的几个关键问题啦,这就是为什么概率全是0的原因:
1. 核心逻辑错误:变量混淆导致判断永远不成立
你定义了两个类似的变量:totalOfRolls(用来存储每次投掷的点数和)和totalOfDiceRolls(初始值为0,之后从来没更新过)。在判断的时候,你写的是:
if(totalOfDiceRolls != counter) { match = match + 0; } else { match ++; }
这里totalOfDiceRolls一直是0,而外层循环的counter从2开始,所以这个判断永远走match +=0的分支,match自然一直是0,概率也就全是0了!应该改成判断totalOfRolls != counter(或者更简洁地直接判断totalOfRolls == counter就累加)。
2. 随机数生成错误:没有使用用户输入的骰子面数
你现在生成骰子点数的代码是:
diceRoll1 = (randNumList.nextInt(11)+1); diceRoll2 = (randNumList.nextInt(11)+1);
这会生成1-12的随机数,但用户输入了diceSides(骰子面数),正确的生成方式应该是randNumList.nextInt(diceSides) + 1,这样才能生成1到diceSides之间的随机数,符合实际骰子的点数范围。
3. match变量没有重置,导致统计累加错误
每次外层循环统计完一个点数和的次数后,match没有重置为0,这样下一个点数和的统计会累加之前的数值,结果完全错误。你需要在外层循环的开头把match重置为0。
4. 整数除法导致概率精度丢失
计算概率的代码(match * 100 / diceRolls)是整数除法,如果match *100不能被diceRolls整除,会丢失小数部分。比如match=30,diceRolls=1000,实际概率是3.0%,但整数除法会得到3,更严谨的方式是转成double计算:(double)match * 100 / diceRolls。
修正后的完整代码
import java.util.Random; import java.util.Scanner; public class DiceProbability { public static void main(String[] args) { Scanner in = new Scanner(System.in); Random randNumList = new Random(); System.out.println("How many sides do the dice have: "); int diceSides = in.nextInt(); System.out.println("How many times will the dice be rolled: "); int diceRolls = in.nextInt(); int highestSum = diceSides * 2; System.out.println("Rolls total | Probability"); // 遍历每个可能的点数和 for (int counter = 2; counter <= highestSum; counter++) { int match = 0; // 每次统计新的点数和时重置match // 进行指定次数的投掷 for (int counter2 = 1; counter2 <= diceRolls; counter2++) { // 生成符合骰子面数的随机点数 int diceRoll1 = randNumList.nextInt(diceSides) + 1; int diceRoll2 = randNumList.nextInt(diceSides) + 1; int totalOfRolls = diceRoll1 + diceRoll2; // 判断当前点数和是否等于目标值 if (totalOfRolls == counter) { match++; } } // 计算概率,用double避免整数除法精度问题 double probabilityOfSum = (double) match * 100 / diceRolls; System.out.printf("%-11d | %.2f%%%n", counter, probabilityOfSum); } in.close(); // 记得关闭Scanner资源 } }
额外优化了几点:
- 去掉了冗余的变量(比如
totalOfDiceRolls、提前声明的diceRoll1等) - 使用
printf格式化输出,让结果排版更整齐 - 关闭了
Scanner资源,避免资源泄漏
内容的提问来源于stack exchange,提问作者CH00CH00CHARLIE

