将数组索引增加1 C#

时间:2015-12-04 18:47:52

标签: c# arrays counter

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

将整数数组的某个索引增加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之间) 然后记下每笔金额出现的频率。

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

3 个答案:

答案 0 :(得分:0)

您可以使用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";
}

答案 1 :(得分:0)

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

import time
import random
import requests
from selenium import webdriver

profile = webdriver.FirefoxProfile()

with open("proxylist.txt") as f: 
     proxy_list = f.read().splitlines()
proxy_ip, proxy_port = random.choice(proxy_list).split(":")

profile.set_preference("network.proxy.type", 1)
profile.set_preference("network.proxy.http", proxy_ip)
profile.set_preference("network.proxy.http_port", int(proxy_port))
profile.update_preferences()
driver = webdriver.Firefox(profile)
driver.get("https://www.ipleak.net")
time.sleep(60)
driver.close()

这需要从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"; } 滚动的次数然后从3个随机数(1-6)循环创建textBox1的次数。并增加数组中的相应位置。由于有16种可能性,阵列初始化为该大小,您只需减去3即可将总和转换为索引,然后添加3以在打印时转换回来。

答案 2 :(得分:0)

//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";
}