首页 > 解决方案 > 如何让while循环与数字生成器一起使用?

问题描述

因此,对于我的练习,我必须使用 srand 函数生成 1 到 100 之间的随机数。我得到了那部分的工作,但是我必须添加一个循环,以便用户可以再次猜测他们是否在第一次尝试时没有正确。我似乎无法使 while 循环工作。

我正在编写文本编辑代码,并通过 Mac 上的终端应用程序使用 Xcode 作为编译器。而且我正在尽我所能使用编程术语——我是新手,所以如果有什么听起来不对劲,那就是原因。

int main()
{
  srand(time(0));
  int randomNumber = 1 + (rand() % 100);
  int humanGuess;


  while (true)
  {
    cout << "Guess a number between 1 and 100!" << endl; 
    cin >> humanGuess;
    cin.ignore(1000, 10);

    if (humanGuess == randomNumber) break; 
    cout << "Great job. You got it! It's " << randomNumber << endl; 

    if (humanGuess >= randomNumber)
    cout << "Too high. Try again!" << endl;

    if (humanGuess <= randomNumber)
    cout << "Too low. Try again!" << endl;
  }//while 
}

没有错误消息,但编译不正确。这是我在终端上运行它时不断得到的:

Guess a number between 1 and 100!
23
Great job. You got it! It's 55
Too low. Try again!
Guess a number between 1 and 100!
78
Great job. You got it! It's 55
Too high. Try again!
Guess a number between 1 and 100!

标签: c++

解决方案


Your code, as shown in the question is (with the break on its own line)

if (humanGuess == randomNumber)
    break;

cout << "Great job. You got it! It's " << randomNumber << endl; 

If the condition humanGuess == randomNumber is true, you break out of the loop with the break statement. Otherwise you unconditionally print "Great job...".

You need to put the printing as a part of the body of the if statement, and break after you print:

if (humanGuess == randomNumber)
{
    cout << "Great job. You got it! It's " << randomNumber << endl; 
    break;
}

推荐阅读