Skip to main content
 首页 » 编程设计

c#之当某些情况发生时,如何在 while 循环中保持变量常量的随机值

2024年02月06日10xing901022

我尝试制作一个基本的猜数字游戏。但是我找不到保持随机数不变的方法,以便为用户提供增加或减少他/她猜测的线索。这对你来说很容易,但我需要你有值(value)和有用的观点。 PS:是的,我是初学者。

 while (true) 
 { 
     Random rd = new Random(); 
 
     Console.WriteLine("guess a number 0-10"); 
 
     guess = int.Parse(Console.ReadLine()); 
 
     comp = rd.Next(10); 
 
     if (guess == comp) 
     { 
         Console.WriteLine("congratz!! u won!!"); 
         Console.WriteLine("press any key to exit"); 
         break; 
     } 
     // Those are the conditions for directing user.I couldn't   implement it. 
 
     //else if (guess > comp) 
     //    Console.WriteLine("your guess is greater than my number, yow!"); 
     //else if (guess < comp) 
     //    Console.WriteLine("your guess is lower than my number, yow!"); 
 
 
     Console.WriteLine("loser!!" + "My number was:" + comp); 
 } 
 Console.ReadLine();    

请您参考如下方法:

你可能想这样走:

Random rd = new Random(); 
int comp = rd.Next(10); // Store you random number before the loop 
int guess = 0; 
int trylimit = 3; 
int round = 0; 
 
while (round < trylimit) 
    { 
        Console.WriteLine("guess a number 0-10"); 
 
        guess = int.Parse(Console.ReadLine()); 
 
        if (guess == comp) 
            { 
                Console.WriteLine("congratz!! u won!!"); 
                Console.WriteLine("press any key to exit"); 
                break; 
            } 
        else if (guess > comp) 
            Console.WriteLine("your guess is greater than my number, yow!"); 
        else if (guess < comp) 
            Console.WriteLine("your guess is lower than my number, yow!"); 
 
            round++; 
    } 
Console.WriteLine("loser!!" + "My number was:" + comp + "\n"); 
Console.ReadLine(); 

正如 Tim Schmelter 在他的评论中所说,您需要在 while 循环 之前声明并初始化 random,否则它可能会在您每次进入循环时发生变化。