C # code only works when using a debugger?

So, here is the code I used. Its just a simple program to check that 3 randomly generated numbers are in ascending or descending order. For some reason, if I use a debugger and enter every line, the code works correctly. If not, he says that the numbers are in the order of 100% or not in the order of 100%, which should not be.

Here is the code I used:

int num1; int num2; int num3; int yes = 0; int no = 0; for (int i = 0; i <= 99; i++) { Random rnd = new Random(); num1 = rnd.Next(1, 11); num2 = rnd.Next(1, 11); num3 = rnd.Next(1, 11); if ( ((num1 <= num2) && (num2 <= num3)) || ((num1 >= num2) && (num2 >= num3)) ) { yes += 1; } else { no += 1; } } Console.WriteLine("The Number are in ascending order " + yes.ToString() + " Times"); Console.WriteLine("The Number are not in ascending order " + no.ToString() + " Times"); Console.ReadLine(); 

I think this might be a pseudo-random problem, and code generating the same 3 numbers every time, but I still learn more about programming, and other help would be greatly appreciated.

+5
source share
2 answers

The constructor new Random() uses the current time as a seed.

If you did not wait in the debugger, all your Random instances have the same seed.

You must use one instance.

+8
source

This is due to how random numbers are generated.

If you take

 Random rnd = new Random(); 

and take it out of the loop, you should see the desired results.

More background:

The random number generator uses the seed depending on the time of its creation. Since your code is running so fast, the seed is the same as the numbers. That's why it works when you walk through.

Creating an instance of Random outside the loop will create it once and uses a random algorithm to generate new numbers.

+5
source

All Articles