You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#猜数字游戏循环中无法生成不同随机数问题求助

解决猜数字游戏的随机数问题

嘿,我来帮你搞定这个猜数字游戏的问题!你的核心问题出在随机数生成的位置不对——你把生成新随机数的代码放在了内部的do-while循环里,导致每次你猜完一个数字,程序立刻就换了一个新的随机数,这自然永远也猜不对啦!

问题根源分析

你看这段代码:

do {
    Console.Write("Enter your guess: ");
    userGuess = Convert.ToInt32(Console.ReadLine());
    // ... 判断高低的逻辑 ...
    numberToGuess = random.Next(100) + 1; // 这里就是坑!
} while (userGuess != numberToGuess);

每次你输入一个猜测值后,程序马上生成了新的numberToGuess,接下来的循环判断userGuess != numberToGuess时,对比的已经是刚生成的新数了,所以永远满足循环条件,一直提示过高或过低。

修正方案

我们需要把生成随机数的操作放在每一局游戏的开头,也就是:

  1. 第一次启动游戏时生成初始随机数
  2. 当用户选择继续游戏时,再生成新的随机数
  3. 内部循环只负责处理当前局的所有猜测,直到猜中为止

修正后的完整代码

static void Main(string[] args) 
{ 
    Random random = new Random(); 
    int numberToGuess;
    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 { 
        // 每一局开始时生成新的随机数
        numberToGuess = random.Next(100) + 1;
        // 内部循环处理当前局的所有猜测
        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."); 
            }
            // 移除这里的随机数生成代码!
        } while (userGuess != numberToGuess); 

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

关键修改点说明

  • 把numberToGuess的生成移到了内部do-while循环的外面,每一局游戏开始时才生成一次
  • 移除了内部循环里的numberToGuess = random.Next(100) + 1;,保证当前局的随机数始终不变
  • 当用户选择继续游戏时,外部循环会再次执行numberToGuess = random.Next(100) + 1;,生成新的随机数开启新一局

这样修改后,程序就能正常运行:每一局用同一个随机数,直到你猜中,然后可以选择开始新的一局,新局用新的随机数~

内容的提问来源于stack exchange,提问作者Zeeshan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:24:59