随机骰子滚动的数学百分比不正确

时间:2015-05-28 18:07:51

标签: java random percentage

所以我有这个代码我正在处理它似乎运行正常,除了打印/显示百分比结果。当百分比相加时,我看到总数不会达到100。我觉得它可能与铸造有关,但是,我不知道错误在哪里并且已经逐步完成了代码倍。如果有人可以帮助我,并给我任何提示结构/任何其他noob东西,我应该知道,请这样做! 我是一个相当新的程序员,不到半年这样做,所以就像我说的任何提示将不胜感激。谢谢!

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);
    }
}

2 个答案:

答案 0 :(得分:4)

你掷骰子的次数少于要求的次数。例如。如果输入3,骰子将只滚动两次。原因是您的for循环条件:

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

一旦到达2而不是3,这将停止循环。这是一个“一个接一个”的错误。尝试:

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

这给了我:

Total percentage shown on the screen in: 100.0

请注意,对于numOfRolls的某些值,由于floating-point errors,它仍然可能不会达到100%。例如。 53卷给了我:

Total percentage shown on the screen in: 99.99999999999999

答案 1 :(得分:0)

该错误位于for函数中的calculatePercentage循环条件语句中。

由于您将上限设置为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);
}