为什么在.NET Fiddle中运行C#代码时生成的随机数会持续变化?
随机数变化原因解答
你给出的示例代码如下:
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; } else if (Guess > Winner) { Console.WriteLine("Guess lower!!"); } else if (Guess < Winner) { Console.WriteLine("Guess higher!!"); } } } }
这段代码本身逻辑不存在问题,Winner变量仅在进入循环前通过r.Next(1, 10)赋值一次,本地运行时数值会保持固定,不会在循环迭代中自行变更。
你观测到的随机数持续变化是在线运行环境的渲染机制导致的错觉:
- 你使用的在线.NET运行工具的交互控制台不会持久化历史输出内容,每次你输入猜测值提交后,平台会重新输出从程序启动到当前节点的所有打印内容,直接覆盖掉之前的控制台展示内容,你看到的过往行里的随机数变化只是重新渲染后的效果,不是代码运行时
Winner变量真的发生了修改。
你可以将代码复制到本地.NET环境中直接运行,即可验证代码逻辑的正确性。
内容的提问来源于stack exchange,提问作者Luke
相关产品推荐
相关产品推荐

