Why does my random number generated keep changing in .NET Fiddle / dotnetfiddle?

454 Views Asked by At

Here's my code:

using System;
using System.Collections.Generic;
                
public class Program
{
    public static void Main()
    {
        Random r = new Random();
        int Winner = r.Next(1, 10);
        bool win = false;
    
        while (win == false)
        {
            Console.WriteLine("Welcome to the game!! Please guess a number between 0 and 10. It is " + Winner + " to win!");
            int Guess = int.Parse(Console.ReadLine());
        
            if (Guess == Winner)
            {
                Console.WriteLine("Well done! " + Guess + " is correct!!");
                win = true;`enter code here`
            }
            else if (Guess > Winner)
            {
                Console.WriteLine("Guess lower!!");
            }
            else if (Guess < Winner)
            {
                Console.WriteLine("Guess higher!!");
            }
        
        }
    
    }
}

The logic works, but the random integer changes each time it goes around the loop.

You can see this here: https://dotnetfiddle.net/vNrvho

Every time the loop goes around & Console.WriteLine("Welcome to the game!! Please guess a number between 0 and 10. It is " + Winner + " to win!") is ran again, the random number in the previous Console.WriteLine changes as well.

Why does the random number keep changing?

1

There are 1 best solutions below

1
On

This is not an issue with your code, but an issue with .NET Fiddle.

You can also see the same issue replicated in another fiddle here, which does something similar: https://dotnetfiddle.net/Mn7mtT

The way that .NET Fiddle works is unknown to me but it's probably sending console output in a request on every input, changing the previous output somehow server-side and then giving you the illusion that the code is running input after input.

However, it's not & it's running the entire code again & again.

This will yield different random values of course and make you think that the value of Winner is changing every time while it isn't.

Verify this by noticing the changing Last Run: value every time you input a new number or by running the code locally outside of .NET Fiddle.

This happens regardless of project type or compiler settings in .NET Fiddle.

The lesson is don't always trust .NET Fiddle!