Java 掷骰子的频率
问题是: 查找600掷骰子的掷骰频率(表示掷骰次数)。 这是我到目前为止的代码,我似乎被困在某个地方,但我就是不知道错误在哪里;如果有人能帮我,那就太好了Java 掷骰子的频率,java,dice,Java,Dice,问题是: 查找600掷骰子的掷骰频率(表示掷骰次数)。 这是我到目前为止的代码,我似乎被困在某个地方,但我就是不知道错误在哪里;如果有人能帮我,那就太好了 public class diceroll { /** * */ public static void main(String[] args) { int toRoll = 600, x,i=0, c1 = 0, c2 = 0, c3 = 0, c4 = 0, c5 = 0,
public class diceroll
{
/**
*
*/
public static void main(String[] args)
{
int toRoll = 600, x,i=0, c1 = 0, c2 = 0, c3 = 0, c4 = 0, c5 = 0,
c6 = 0;
double pct1, pct2, pct3, pct4, pct5, pct6;
for (i=0;i<=toRoll; i++)
{
x = (int)(Math.random()*6)+1;
if (x==1)
c1++;
else if (x==2)
c2++;
else if (x==3)
c3++;
else if (x==4)
c4++;
else if (x==5)
c5++;
else if (x==6)
c6++;
}
pct1 = (c1 * 100.0) / (double)toRoll;
pct2 = (c2 * 100.0) / (double)toRoll;
pct3 = (c3 * 100.0) / (double)toRoll;
pct4 = (c4 * 100.0) / (double)toRoll;
pct5 = (c5 * 100.0) / (double)toRoll;
pct6 = (c6 * 100.0) / (double)toRoll;
System.out.printf("Face\tFrequency\t%\n");
System.out.printf("-------------------\n");
System.out.printf("1\t%d\t%10.1f\n", c1);
System.out.printf("2\t%d\t%10.1f\n", c2);
System.out.printf("3\t%d\t%10.1f\n", c3);
System.out.printf("4\t%d\t%10.1f\n", c4);
System.out.printf("5\t%d\t%10.1f\n", c5);
System.out.printf("6\t%d\t%10.1f\n", c6);
}
}
公共类掷骰子
{
/**
*
*/
公共静态void main(字符串[]args)
{
int toRoll=600,x,i=0,c1=0,c2=0,c3=0,c4=0,c5=0,
c6=0;
双pct1、pct2、pct3、pct4、pct5、pct6;
对于(i=0;i使用Random.nextInt(6),而不是Math.Random()*6
如有疑问,请参阅以了解原因。您在打印时遗漏了pctx
值
尝试打印
System.out.printf("1\t%d\t%10.1f\n", c1, pct1);
...
您的问题是打印输出完全错误
打印%%
符号的正确方法是使用%%
,请参阅javadoc。在不转义此变量的情况下,它认为您试图使用某些特殊语法。修复后,您需要打印实际百分比,而不是当前使用的滚动计数
System.out.printf("Face\tFrequency\t%%\n");
System.out.printf("-------------------\n");
System.out.printf("1\t%f\t%%10.1f\n", pct1);
System.out.printf("2\t%f\t%%10.1f\n", pct2);
System.out.printf("3\t%f\t%%10.1f\n", pct3);
System.out.printf("4\t%f\t%%10.1f\n", pct4);
System.out.printf("5\t%f\t%%10.1f\n", pct5);
System.out.printf("6\t%f\t%%10.1f\n", pct6);
也是小问题,
你不需要在这里投替身
pct1=(c1*100.0)/(double)toRoll;
应成为
pct1=(c1*100.0)/toRoll;
获得从1到6的随机数的首选方法是
随机。nextInt(6)+1
症状是什么?你做了什么调试?System.out.printf需要另一个参数。浮点参数。我看不出有问题。