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

时间:2017-08-19 16:51:48

标签: java

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

编写一个程序来模拟两个骰子的滚动。程序应该使用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.util.Random;

public class dice_roll {
public static void main(String [] args){

    Random rand = new Random();
    int dice1, dice2;
    int [] frequency = new int [13];
    int [] rolls = new int [13];
    int sum;
    double percentage;

    for (int i = 0; i <= 36000; i++) {
        dice1 = rand.nextInt(6)+1; 
        dice2 = rand.nextInt(6)+1;
        frequency[dice1+dice2]++;
        sum = dice1 + dice2;
    }
    System.out.printf("Sum\tFrequency\tPercentage\n");
    for (int i = 2; i < frequency.length; i++) {
         percentage = (frequency[i] * 100.0) / 36000;
         System.out.printf("%d\t%d\t\n",i,frequency[i]);//this line here
    }
}

}

2 个答案:

答案 0 :(得分:1)

首先,你的for循环是1:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="newpost" class="newcontent">
    Test Content   
</div>

<div class="livechat-button">Open</div>

您的for (int i = 0; i <= 36000; i++) { // ^ // remove this "=" or you will loop 36001 times 似乎是多余的,因此请将其删除。

我认为你只是不知道如何格式化输出,以便浮点数正确到2 d.p.正确?

这很容易。只需添加do sum

你的printf就像:

%.2f

您的代码的另一个问题是它可能会产生未对齐的内容。它也不会将值与右侧对齐,如示例输出所示。要解决这个问题,您还需要更改printf。像这样:

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

如果您想了解有关printf如何工作的更多信息,请列出here

答案 1 :(得分:0)

this answer窃取:我们可以使用padRight定义为:

public static String padRight(String s, int n) {
    return String.format("%1$-" + n + "s", s);
}

并且做:

System.out.printf("Sum\tFrequency\tPercentage\n");
for (int i = 2; i < frequency.length; i++) {
    String s = padRight(String.valueOf(i), 4);
    String f = padRight(String.valueOf(frequency[i]), 12);
    percentage = (frequency[i] * 100.0) / 36000;
    String p = String.format("%.2f", percentage); // This formatting will keep two digits after the point
    System.out.printf("%s%s%s\n", s ,f, p);
}

输出(示例)

Sum Frequency   Percentage
2   992         2.76
3   2031        5.64
4   3034        8.43
5   3947        10.96
6   4887        13.58
7   5948        16.52
8   4965        13.79
9   4051        11.25
10  3014        8.37

您可以使用它并从第一行中删除\t并使用空格来创建列之间所需的间距量,然后将调用中的第二个参数传递给{{1因此。