In my code, I am trying to generate 5 numbers. If any of the numbers equal to 4, then I want to store that 4 into an array. Currently I'm having trouble and my code will not store the 4 into the array.
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();
}
This:
total +=fours[i]
Will attempt to increment total with the int found at index i of your array (which will currently be 0, because int defaults to 0).
This:
fours[i] = 4;
Is how you assign 4 to the ith index in your array.
Read about how the assignment operator works in C#
The = operator is called the simple assignment operator. It assigns the value of the right operand to the variable, property, or indexer element given by the left operand.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With