2014-09-24 38 views
-1

所以下面是編碼: •設計,實現,測試和調試一個C#程序,用於顯示兩個骰子總數爲100卷的頻率。包括以下內容:C#上的頻率代碼錯誤#

  1. 聲明一個數組,表示兩個骰子拋出的可能結果。

  2. 對於文件中的每個條目,增加與該結果對應的數組元素。

  3. 最後,顯示頻率計數爲模擬

但我得到的錯誤:

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); 

    } 
+0

問題是你沒有在'Frequency.Items []'數組中分配足夠的元素。當你滾動一個12時,你減去2得到一個10的索引,但是你只爲索引0到9創建了空間。 – 2014-09-24 01:29:17

+0

@BrianRogers - 那麼我該如何解決這個問題? – LaTachuela 2014-09-24 01:59:35

+0

查看Rufus L的回答。 – 2014-09-24 14:56:38

回答

1

的問題是,當您需要11.記住,這兩個「2」和「12」只分配10個插槽包容性,所以有11點的可能性,而不是10

// item count: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 
// list index: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 
// dice sum: 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 

試試這個:

for (i = 0; i < 11; i++) //index starts at 0 and ends at 10 (11 indexes) 
{ 
    FrequencySum.Items.Add("0"); //Frequency values between 2 and 12. 
} 

這裏:

for (i = 0; i < 11; i++) 
{ 
    total += int.Parse(FrequencySum.Items[i].ToString()); 
} 
+0

謝謝你Rufus L,我試過你的編碼,它工作。 – LaTachuela 2014-09-24 02:31:14

1

你的骰子值的確是2和12之間,但有11個值合計,不10.所以,你應該有11個零初始化列表,而不是10 顯然,這適用於計數總計也是如此。

你犯的錯誤是如此普遍,它有自己的名稱:Off-by-one error

+0

更改代碼以使其工作的最佳方法是什麼? – LaTachuela 2014-09-24 02:00:35