无法在循环中创建不同的随机数

时间:2018-01-09 12:33:06

标签: c#

我是C#的新手,在我创建的这个随机猜测游戏中,我很难理解我哪里出错了。我试图在第30行的do while循环中添加一个random.next命令,当我运行程序时它说我的猜测太高或太低,我不明白出了什么问题。这是未完成的代码:

    static void Main(string[] args)
    {
        Random random = new Random();
        int numberToGuess = random.Next(100) + 1;
        int userGuess = 0;
        string name;

        Console.WriteLine("What is your name?");
        name = Convert.ToString(Console.ReadLine());

        Console.WriteLine("In this game you need to guess which number the computer has picked in the range of 1 to 100."
            + Environment.NewLine + "If the number you enter is too high or too low the program will display this, " +
            Environment.NewLine + "try to make the least amount of guesses as possible!" + Environment.NewLine 
            + "==========================================================================================================");

        do
        {

            do
            {
                Console.Write("Enter your guess: ");
                userGuess = Convert.ToInt32(Console.ReadLine());

                if (userGuess > numberToGuess)
                {
                    Console.WriteLine(userGuess + " is too high!");
                }
                else if (userGuess < numberToGuess)
                {
                    Console.WriteLine(userGuess + " is too low!");
                }
                else
                {
                    Console.WriteLine(userGuess + " SPOT ON! Congratulations.");
                }

                numberToGuess = random.Next(100) + 1;

            } while (userGuess != numberToGuess);

            Console.WriteLine("Do you want to continue?");
        } while (Console.ReadLine().ToUpper() == "YES");


    }

如果我删除numberToGuess = random.Next(100)+ 1;代码工作正常,但重复相同的随机数。

请帮助。

3 个答案:

答案 0 :(得分:0)

您的猜测范围是非常高的1到100,并且每次您再次生成随机数。只需缩小随机生成器编号的大小,例如

 int numberToGuess = random.Next(5) + 1;

首先检查其是否有效,然后考虑扩展它。

答案 1 :(得分:0)

调试您的应用程序替换

Console.Write("Enter your guess: ");

使用

Console.Write("Enter your guess (" + numberToGuess + "): ");

你会看到numberToGuess每次都在改变......你应该评论那条线并只使用生成的第一个随机数。

答案 2 :(得分:-3)

此方法将返回一个真正随机的数字。

Public Shared Function RandomInteger(min As Integer, max As Integer) As Integer Dim Rand As New System.Security.Cryptography.RNGCryptoServiceProvider Dim scale As UInteger = UInteger.MaxValue While scale = UInteger.MaxValue ' Get four random bytes. Dim four_bytes As Byte() = New Byte(3) {} Rand.GetBytes(four_bytes)

            ' Convert that into an uint.
            scale = BitConverter.ToUInt32(four_bytes, 0)
        End While

        ' Add min to the scaled difference between max and min.
        Return CInt(min + (max - min) * (scale / CDbl(UInteger.MaxValue)))
    End Function

' Convert that into an uint. scale = BitConverter.ToUInt32(four_bytes, 0) End While ' Add min to the scaled difference between max and min. Return CInt(min + (max - min) * (scale / CDbl(UInteger.MaxValue))) End Function