gpt4 book ai didi

c++ - 如何让 while 循环与数字生成器一起工作?

转载 作者:行者123 更新时间:2023-11-30 03:14:58 25 4
gpt4 key购买 nike

因此,对于我的练习,我必须使用 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!

最佳答案

如问题所示,您的代码是(break 单独一行)

if (humanGuess == randomNumber)
break;

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

如果条件 humanGuess == randomNumber 为真,则使用 break 语句跳出循环。否则你无条件地打印“干得好...”

您需要将打印作为if 语句主体的一部分,并在打印后break:

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

关于c++ - 如何让 while 循环与数字生成器一起工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57354642/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com