[英]Rolling m die with n sides x times
好的,所以我更改了代碼,並刪除了其中很多不必要的垃圾。 它適用於某些數字,但不適用於其他數字,例如,當我放入100卷/ 8面/ 3模時,盡管我為此設置了限制,但仍給我帶來了超出范圍的錯誤。 顯然,我已經查看了一些細節,但是我不確定它是什么細節。
public class Ass11f {
public static void main(String[] args) {
EasyReader console = new EasyReader();
System.out.print("Enter how many times you want to roll the die: ");
int numRolls = console.readInt();
System.out.print("Enter the amount of sides: ");
int numSides = console.readInt();
System.out.print("Enter the amount of die: ");
int numDie = console.readInt();
int[] rollSum = new int[numDie*numSides];
for (int i = 0; i<numRolls; ++i)
{
int rollCounter=0;
for (int l = 0; l<numDie; ++l){
rollCounter += ((int)(Math.random()*numSides)+1);
}
rollSum[rollCounter]++;
}
for (int m = 2;m<=rollSum.length;++m) System.out.println(m+"'s: "+rollSum[m]+" times, "+((((double)rollSum[m])/numRolls)*100)+"%");
}
}
有兩個基本問題:
m<=rollSum.length
最終將執行的操作。 將其替換為m < rollSum.length
以使其在最終值之前停止。 另外,以下是一些使數組創建更加清晰的方法:
// The minimum value is always numDie.
// The maximum is always numDie * numSides
// There are maximum - minimum + 1 possible values (ie 6 on a d6)
int maximum = numDie * numSides;
int minimum = numDie;
// Remember, index zero is now the minimum roll.
// The final index is the maximum roll. So the count at an index is really
// the count for any roll with value index + minimum
int[] rollSum = new int[maximum - minimum + 1];
我還建議拆分該打印語句。 它更易於閱讀和調試。 另外,您可以從numDie而不是2開始,以說明您的骰子死於或少於3:
for (int i = numDie; i < rollSum.length; ++i) {
// Print the first bit, ie "2's: ".
System.out.print(i + "'s: ");
// How many times was that value rolled?
System.out.print(rollSum[i] + " times, ");
// What percentage is that?
double percentage = ((double)rollSum[i]) / numRolls * 100;
System.out.println(percentage + "%");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.