如果我有一个数字的总和和频率,我该如何创建百分比?

时间:2017-03-27 14:34:51

标签: java percentage

我无法获得频率的百分比。以下是问题:

编写一个程序来模拟两个骰子的滚动。程序应该使用Random类的对象来滚动第一个die并再次滚动第二个die。然后应计算两个值的总和。每个骰子可以显示1到6的整数值,因此值的总和将在2到12之间变化,其中7是最频繁的总和,2和12是最不频繁的总和。你的应用程序应掷骰子36,000次。使用一维数组来跟踪每个可能总和出现的次数。 显示在表格格式的结果。确定总数是否合理(例如,这里有六种滚动方式,因此大约六分之一的滚动应该是7)。 样本输出:

Sum   Frequency  Percentage
  2        1027        2.85
  3        2030        5.64
  4        2931        8.14
  5        3984       11.07
  6        5035       13.99
  7        5996       16.66
  8        4992       13.87
  9        4047       11.24
 10        2961        8.23
 11        1984        5.51
 12        1013        2.81

到目前为止,这是我的代码:

import java.security.SecureRandom;

public class DiceSum {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        SecureRandom random = new SecureRandom();

        int dice1, dice2;
        int [] frequency = new int [13];
        int [] rolls = new int [13];
        int sum;
        int percentage;

        for (int i = 0; i <= 36000; i++) { // runs 36000 times

            dice1 = random.nextInt(6)+1; // generates a random number
            dice2 = random.nextInt(6)+1;

            frequency[dice1+dice2]++;

            sum = dice1 + dice2; // creates the sum of dice 1 and dice 2

        }

        System.out.printf("Sum\tFrequency\tPercentage\n");

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

            percentage = (frequency * 100.0) \ 36000; //This is the line 

            System.out.printf("%d\t%d\t\n",i,frequency[i]);

        } // end of for loop

    } // end of main

} // end of class

1 个答案:

答案 0 :(得分:0)

我建议更改行

text

percentage = (frequency * 100.0) \ 36000;

frequency [i]将从频率中获取第i个元素。