C#上的频率代码错误

本文关键字:代码 错误 频率 | 更新日期: 2023-09-27 18:24:12

下面是的编码:•设计、实现、测试和调试C#程序,以显示100次掷骰子的两个骰子之和的频率。包括以下内容:

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

C#上的频率代码错误

问题是,当您需要11个插槽时,您只分配了10个插槽。记住"2"answers"12"都包含在内,所以有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());
}

您的骰子值确实在2到12之间,但总共有11个值,而不是10个。所以你应该用11个零来初始化你的列表,而不是10个。这显然也适用于总数的计算。

你犯的错误很常见,它有自己的名字:一个错误关闭