dimanche 10 octobre 2021

Random number generated keeps changing in .NET Fiddle / dotnetfiddle

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.

How do I get the random number to not change?




Aucun commentaire:

Enregistrer un commentaire