c++ - 如何让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!
解决方案
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;
}
推荐阅读
- javascript - 无法从同级目录导入图像 - React Native
- android - 如何将类类型分配给任何类型的arraylist?
- azure - 将 Django 应用程序部署到 Azure 成功,但显示默认 django 页面,而不是我的应用程序
- next.js - 如何将所有路由参数提供给 getStaticPaths?
- r - 逐行检测序列
- android - 我无法在 Android 上使图像透明?
- powerbi - PowerBi 嵌入令牌:操作返回无效状态代码“BadRequest”
- python - 我可以使用 allennlp.modules.elmo.Elmo 从头开始训练 ELMo 模型吗?
- pytest - pytest - 更改某些测试文件的夹具范围
- css - 如果存在侧边栏,则为 3 列布局或 2 列布局