Running the program gives me different results in debug mode

I have provided a simple code that will output 10 random digits that are between 0 and 100. When I run this in visual studio (C #) using F5, I get the same number 10 times. However, if I run it in debug mode, using F10 or F11 line by line, I get 10 different numbers (maybe not all are different, but they are randomized).

public static void rand() { for (int j = 0; j < 10; j++) { Random r = new Random(); Console.WriteLine( r.Next(100)); } } 

I know how to fix the problem of creating an instance of Random r outside the loop and copying by reference, but I would like to understand why this is happening. I think this has something to do with the seed, but the program works while working in debug mode, which bothers me.

Also, now I am wondering if I need to always check if the debug mode gives me the correct results.

+7
source share
1 answer

You must create instances of the Random instance before the loop.

 public static void rand() { Random r = new Random(); for (int j = 0; j < 10; j++) { Console.WriteLine(r.Next(100)); } } 

And here is the explanation:

... The initial default value is derived from the system clock and has a final resolution. As a result, various Random objects that are created in close sequence when the default constructor is called will have the same initial default values ​​and, therefore, will create the same sets of random numbers. This problem can be avoided by using one random object to generate all random numbers. ...

If you want to use different instances of Random , you must use different seed values. For example, the variable j :

 public static void rand() { for(int j = 0; j < 10; j++) { Random r = new Random(j); Console.WriteLine(r.Next(100)); } } 

Answering your question: ... if I always need to check if the debug mode gives me the correct results.

No, you do not need to doubt the results of debug mode. They are right. Your understanding of them may be wrong.

+10
source

All Articles