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