随机掷骰子的百分比数学计算不正确

Percentage math not coming out correctly for random dice roll

所以我正在处理这段代码,它似乎 运行 正确,除了打印/显示百分比结果。当百分比相加时,我看到总数加起来不等于 100。我觉得这可能与转换有关,但是,我看不出错误在哪里,并且已经多次遍历代码。如果有人可以帮助我并给我任何关于结构化的提示/我应该知道的任何其他新手的东西,请这样做! 我是一个相当新的程序员,做这件事还不到半年,所以就像我说的那样,任何提示都将不胜感激。谢谢!

import java.util.Random;
import java.util.Scanner;

public class DiceRoller {

    public static void main(String[] args) {
        calculatePercentage();
    }

    //Get roll number from user
    static int getNumOfRolls(){
        Scanner input = new Scanner(System.in);

        System.out.println("How many times would you like to roll the dice?");
        int numOfRolls = input.nextInt();
        return numOfRolls;

    }
    //use object from class random to assign var value from 1 - 6 inclusive
    static int rollDice(){

        Random rand = new Random();
        int die = (rand.nextInt(6) + 1);

        return die;
    }

    static void printPercentage(int[] dieTotal, int numOfRolls){

        double totalPer = 0;
        double percent = 0;

        for(int i = 2; i < dieTotal.length; i++){

            int curNum = dieTotal[i];

            percent = ((curNum / (double)numOfRolls) * 100);
            totalPer += percent;
            System.out.printf("%d was rolled %.2f %% of the time. \n", i, percent);
        }

        System.out.println("Total percentage shown on the screen in: " + totalPer);
    }

    //store values of dice in an array. Call printPercent method defined above.
    static void calculatePercentage(){
        int numOfRolls = getNumOfRolls();

        int die1 = 0;
        int die2 = 0;
        int[] dieTotal = new int[13];

        for(int i = 0; i < numOfRolls - 1; i++){
            die1 = rollDice();
            die2 = rollDice();
            int total = die1 + die2;

            dieTotal[total]++;

        }

        printPercentage(dieTotal, numOfRolls);
    }
}

您掷的骰子比要求的次数少了一次。例如。如果输入 3,则骰子只会掷两次。原因是你的 for 循环条件:

for(int i = 0; i < numOfRolls - 1; i++){

一旦达到 2 而不是 3,这将停止循环。这是一个 "off by one" 错误。尝试:

for(int i = 0; i < numOfRolls; i++){

这给了我:

Total percentage shown on the screen in: 100.0

请注意,由于 floating-point errors,某些值 numOfRolls 加起来可能仍达不到 100%。例如。 53 rolls 给我:

Total percentage shown on the screen in: 99.99999999999999

错误出在 calculatePercentage 函数中的 for 循环条件语句中。

由于您将上限设置为 i < numOfRolls -1,因此您只会获得 n-1 的掷骰数。进行以下更改:

static void calculatePercentage(){
    int numOfRolls = getNumOfRolls();

    int die1 = 0;
    int die2 = 0;
    int[] dieTotal = new int[13];

    for(int i = 0; i < numOfRolls; i++){
        die1 = rollDice();
        die2 = rollDice();
        int total = die1 + die2;

        dieTotal[total]++;

    }

    printPercentage(dieTotal, numOfRolls);
}