0
我正在写一个初学者程序,使用数组,math.random和和随机发生器来计算2个die的总和,并滚动一定的时间。铸造一个int数组到一个double来计算百分比
我想计算一个总和出现的次数百分比,需要2个小数位。有没有办法将(?)和数组转换为2位小数?
另外,当我在屏幕上打印节目时,它显示每个总和120次。我不明白为什么
这是我到目前为止有:
import java.util.Random;
import java.util.Scanner;
public class Die {
public static void main(String[] args){
int faces;
int face1;
int face2;
int face3;
int face4;
int times;
int index;
int sum;
Scanner scan = new Scanner(System.in);
Random rand = new Random();
System.out.println("%-0-1-2-3-4-5-6-7-8-9-0-1-2-3-4-5-6-7-8-9-0-%");
System.out.println("%\t\t\t\t\t %");
System.out.println("% How good is the Random Number Generator %");
System.out.println("%\t\t\t\t\t %");
System.out.println("%-0-1-2-3-4-5-6-7-8-9-0-1-2-3-4-5-6-7-8-9-0-%");
System.out.println();
System.out.print("What is the number of sides of each die? ");
faces = scan.nextInt();
System.out.print("How many times do you want to roll the dice ?");
times = scan.nextInt();
int[]rollCount = new int[(faces*2) + 1];
for (int i = 0; i<rollCount.length; i++)
rollCount[i] = 0;
int dice1=faces;
for (int k=1; k<=dice1; k++){
int dice2=faces;
for (int r=1; r<=dice2; r++){
rollCount[k+r]++;
for (int roll = 0; roll <times; roll++){
}
}
}
int[]rollCountRand = new int[(faces*2) + 1];
for (index = 0; index <rollCountRand.length; index++)
rollCountRand[index] = 0;
for (int roll = 0; roll<=times; roll++){
face1 = 1 + rand.nextInt(faces);
face2 = 1 + rand.nextInt(faces);
rollCountRand[face1 + face2]++;
}
int[]rollCountMath = new int [(faces*2)+1];
for (int i=0; i<rollCountMath.length; i++)
rollCountMath[i] = 0;
for (int j=0; j<=times; j++){
face3 = (int)(faces* Math.random() + 1);
face4 = (int)(faces* Math.random() + 1);
sum = face3 + face4;
rollCountMath[sum]++;
}
for (int r = 2; r <rollCount.length; r++){
int percent = (rollCount[r]/((faces*faces)*100));
for (int k = 2; k <rollCountRand.length; k++){
int percentOne = rollCountRand[k]/(times/100);
for (int q = 2; q <rollCountMath.length; q++){
int percentTwo =rollCountMath[q]/(times/100);
System.out.print(r + "\t(" + rollCount[r] + ")" + "\t" + "%" + percent + "\t" + k + "\t(" + rollCountRand[k]+")" + "\t"+"%"+percentOne + "\t" + q + "\t(" + rollCountMath[q]+")" + "\t" + "%"+percentTwo);
System.out.println();
谢谢!
'Math.random'和'Random'? – Jon 2012-03-19 20:07:13
是的,看看它们是否匹配 – user1279434 2012-03-19 20:14:43
你不能从int中“投射”整个数组到两倍。数组中的值是'int'值,即使在C语言中实际允许投射(或者至少不会导致编译错误)的语言也不会奇迹般地改变。如果你想浮点数值使你的浮点类型的元素数组。 – 2012-03-19 20:21:23