2
Console.WriteLine("How many times would you like to roll?");
string count = Console.ReadLine();
int cnt = Convert.ToInt32(count);

for (int i = 1; i <= cnt; i++)
{
    int rol = new int();
    Random roll = new Random();
    rol = roll.Next(1, 6);
    Console.WriteLine("Die {0} landed on {1}.", i, rol);
}

Console.ReadLine();

I am trying to create a dice-rolling simulator in C#, but I'm encountering one problem: The random number never changes after the first roll. What is happening and how can I fix it?

Alex
  • 13,024
  • 33
  • 62
qualia
  • 29
  • 5

2 Answers2

2

As Alex pointed you need to move it out of the for loop. Also use 1,7 instead of 1,6 that way you will get results from 1 to 6.

Console.WriteLine("How many times would you like to roll?");
string count = Console.ReadLine();
int cnt = Convert.ToInt32(count);
Random roll = new Random();
for (int i = 1; i <= cnt; i++) {
  int rol = new int();

  rol = roll.Next(1, 7);
  Console.WriteLine("Die {0} landed on {1}.", i, rol);
}
Console.ReadLine();
Nathan Tuggy
  • 2,237
  • 27
  • 30
  • 38
Muhammad Ali
  • 3,478
  • 5
  • 19
  • 30
0

Random creates pseudo-random numbers one by one. This sequence of random numbers is controlled by the seed number. Two sequences of random numbers will be identical if their seeds are identical. The numbers within the sequence are random: in a sense that you can't predict the next number in the sequence.

In case of Random, where does the seed come from? It depends on which constructor was used. Random() creates a default seed. Random(Int32) uses the seed passed by the calling code.

The code in the O.P. creates a new random number generator object in every iteration of the loop. Every time, the seed is the same default. Every time, the first number in the sequence of pseudo-random numbers is the same.

So, create one Random outside of the loop and use the same Random for every iteration of the loop.

        Console.WriteLine("How many times would you like to roll?");
        string strCount = Console.ReadLine();
        int n = Convert.ToInt32(strCount);

        Random die = new Random();
        for (int i = 1;  i <= n;  i++)
        {
            int roll = die.Next(1, 6);
            Console.WriteLine("Die {0} landed on {1}.", i, roll);
        }

        Console.ReadLine();
Nick Alexeev
  • 1,688
  • 2
  • 22
  • 36