猜猜数字C#游戏

时间:2014-07-05 18:46:17

标签: c#

我需要写一个'猜数字'程序包括1-100之间的数字,包括While循环。它还需要告诉用户他们最后有多少猜测,我坦率地不知道如何做到这一点。此外,用户必须在程序响应之前键入他们的猜测3次,并告诉他们是否高于或低于随机数。 这是我的代码:

Random RandomClass = new Random();
int x = RandomClass.Next(1, 100);
Console.WriteLine("I am thinking of a number between 1-100. Can you guess what it is?");
int guess = 0;
while (guess != x)
{
  guess = Convert.ToInt32(Console.ReadLine()); // ReadLine 1
  if (guess == x)
  {
    Console.WriteLine("Well done! The answer was " + x + " and you found it in XXXX guesses");
    Console.ReadLine(); // ReadLine 2
  }
  else if (guess != x)
  {
    if (guess < x)
    {
      Console.WriteLine("No, the number I am thinking of is higher than " + guess + ". Can you guess what it is?");
      Console.ReadLine(); // ReadLine 3
    }
    else if (guess > x)
    {
      Console.WriteLine("No, the number I am thinking of is lower than " + guess + ". Can you guess what it is?");
      Console.ReadLine(); // ReadLine 4
    }
  }
  Console.ReadLine(); // ReadLine 5.
}

以下是我调试时的样子:

I am thinking of a number between 1-100. Can you guess what it is?
50
50
50
No, the number I am thinking of is lower than 50. Can you guess what it is? 
40
40
40
No, the number I am thinking of is higher than 40. Can you guess what it is?
45
45
45

等等。

1 个答案:

答案 0 :(得分:1)

我冒昧地在ReadLine来电时添加号码,同时改善问题的格式,让我们看看上面输出中的第二个条目。 40进入三次。这三个输入对应于Readline()调用4,5和&amp; 1。

只有ReadLine()调用1实际获取任何数据,其他数据应被删除。

对于尝试次数,您应该添加一个在循环中每回合递增的变量

// --- Snip ---
int guess = 0;
int guessCount = 0;
while (guess != x)
{
  guessCount++; // Increase guessCount with one for each turn of the loop.
  guess = Convert.ToInt32(Console.ReadLine()); // ReadLine 1
// --- Snip ----