如何将数字存储到数组中?

时间:2015-04-26 04:00:30

标签: c# arrays

在我的代码中,我试图生成5个数字。如果任何数字等于4,那么我想将4存储到数组中。目前我遇到了麻烦,我的代码不会将4存储到数组中。

static void Main()
    {
        Random rand = new Random();
        int total = 0, randInt;

        Console.WriteLine("The computer is now rolling their dice...");
        int[] fours = new int[total];

        for (int i = 0; i < 5; i++)
        {
            randInt = rand.Next(10);
            Console.WriteLine("The computer rolls a {0:F0}", randInt);
            if (randInt == 4)
            {
                total +=fours[i]; //Here I am trying to store the 4 into the array of 'fours'.

            }

        }

        Console.WriteLine(total); //This currently prints to 0, regardless of any 4's the random number generator has generated. I want this to print out how many 4's I have rolled.
        Console.ReadLine();
    }

1 个答案:

答案 0 :(得分:3)

此:

total +=fours[i]

将尝试使用在数组的索引total找到的int递增i(当前为0,因为int默认为0)。

此:

fours[i] = 4;

如何为数组中的第i个索引分配4。

了解assignment operator在C#中的工作原理

  

=运算符称为简单赋值运算符。它将右操作数的值赋给由左操作数给出的变量,属性或索引器元素。