所以下面是編碼: •設計,實現,測試和調試一個C#程序,用於顯示兩個骰子總數爲100卷的頻率。包括以下內容:C#上的頻率代碼錯誤#
聲明一個數組,表示兩個骰子拋出的可能結果。
對於文件中的每個條目,增加與該結果對應的數組元素。
最後,顯示頻率計數爲模擬
但我得到的錯誤:
InvalidArgument=Value of '10' is not valid for 'index'.
Parameter name: index.
我把***
讓您知道消息被顯示爲一塊編碼。我不明白我做錯了什麼。請幫忙。
private void createButton_Click(object sender, EventArgs e)
{
int[] rollArray = new int[100]; //Creates Array for holding rolls.
int i;
int dice1; //Dice 1
int dice2; //Dice 2
int total; //Dice Totals.
int index;
int rollValue;
FrequencySum.Items.Clear();
for (i = 0; i < 10; i++) //index numbering starting at 0.
{
FrequencySum.Items.Add("0"); //Frequency values between 2 and 12.
}
for (i = 0; i < 100; i++) //100 Dice Rolls, indexing starts at 0, there is 100 & Loop.
{
dice1 = diceRoll.Next(6) + 1; //Rolls Dice 1
dice2 = diceRoll.Next(6) + 1; //Rolls Dice 2.
rollValue = dice1 + dice2; //value of the rolls for dice 1 and dice 2.
index = rollValue - 2; //roll 2 is item 0 and roll 12 is item 10.
-----►FrequencySum.Items[index] = (int.Parse (FrequencySum.Items[index].ToString())+ 1).ToString(); *** ◄------- this is where the error comes up
}
total = 0; //Displays total of rolls.
for (i = 0; i < 10; i++)
{
total += int.Parse(FrequencySum.Items[i].ToString());
}
FrequencySum.Items.Add(total);
}
問題是你沒有在'Frequency.Items []'數組中分配足夠的元素。當你滾動一個12時,你減去2得到一個10的索引,但是你只爲索引0到9創建了空間。 – 2014-09-24 01:29:17
@BrianRogers - 那麼我該如何解決這個問題? – LaTachuela 2014-09-24 01:59:35
查看Rufus L的回答。 – 2014-09-24 14:56:38