将数组索引增加1 C#

本文关键字:增加 索引 数组 | 更新日期: 2023-09-27 18:25:38

我有一个用于计数的整数数组。

将整数数组的某个索引增加1的最简单方法是什么?

我的代码现在是这样的。

input = Convert.ToInt32(textBox1.Text);
number1 = rand.Next(1, 7);
number2 = rand.Next(1, 7);
number3 = rand.Next(1, 7);
//array used to keep track of how many times a certain number has showed up
int[] counters = new int[14];
int sum = number1 + number2 + number3;
for (int i = 0; i <= input; i++)
{
    counters[sum] = counters[sum] + 1; //counters[sum]++;???
}
for (int i = 0; i < 14; i++)
{
    richTextBox1.Text += "The number " + (i + 1) + "showed up" + counters[i] + " times'n";
}

我做错了什么?为什么我不能:

array[i]++;    or     array[i] = array[i] + 1; ???

编辑以保持清晰。

我想做的事:

滚动3个骰子,只要用户想要

将3个骰子掷在一起求和(总和应在3-18之间)然后记下每个总数出现的频率。

最后以%显示每个数字出现的次数。

将数组索引增加1 C#

听起来您真正想要的是以下内容。

Random rand = new Random();
int numberOfRolls = Convert.ToInt32(textBox1.Text);
int[] counters = new int[16]; //16 different possible sums (3 to 18)
for (int i = 0; i < numberOfRolls; i++)
{
    int sum = rand.Next(1, 7) + rand.Next(1, 7) + rand.Next(1, 7);
    counters[sum - 3]++;
}
for (int i = 0; i < 16; i++)
{
    richTextBox1.Text += "The number " + (i + 3) + " showed up " + counters[i] + " times'n";
}

这需要从textBox1滚动的次数,然后循环该次数,从3个随机数创建sum(1-6)。并递增数组中的相应位置。由于有16种可能性,数组的首字母缩写为该大小,您只需减去3即可从总和转换为索引,然后在打印时加3即可转换回。

您可以使用linq和List来完成此操作,请参阅以下代码:

input = Convert.ToInt32(textBox1.Text);
for(var i = 0; i < input; i++)
{
    number1 = rand.Next(1, 7);
    number2 = rand.Next(1, 7);
    number3 = rand.Next(1, 7);
    //array used to keep track of how many times a certain number has showed up
    int sum = number1 + number2 + number3;
    sums.Add(sum); //Where sums is a List<int>
}
var report = sums.GroupBy(i => i).Select(g => new { TimesShowedUp = g.Count(), Sum = g.Key });
foreach(var r in report)
{
    richTextBox1.Text += "The number " + r.Sum + "showed up" + r.TimesShowedUp + " times'n";
}
//array used to keep track of how many times a certain number has showed up
int[] counters = new int[15];
iterations = Convert.ToInt32(textBox1.Text);
for (int i = 1; i <= iterations; i++)
{
    number1 = rand.Next(1, 7);
    number2 = rand.Next(1, 7);
    number3 = rand.Next(1, 7);
    int sum = number1 + number2 + number3;
    counters[sum-3]++;
}
for (int i = 0; i <= 15; i++)
{
    richTextBox1.Text += "The number " + (i + 3) + " showed up " + counters[i] + " times'n";
}