我今晚开始尝试学习C ++,而现在我只是在IDE中搞乱。如何使这个简单的程序在您猜到正确的数字(5、6或7)之前不关闭程序?
按现状显示,只需输入一次,然后说按任意键关闭即可,而不是让我继续猜测。
#include <iostream>
int main()
{
int favorite_number;
std::cout << "Enter your favorite number between 1 and 100: ";
std::cin >> favorite_number;
if(favorite_number == 5 || favorite_number == 6 || favorite_number == 7)
{
std::cout << "Amazing!! That's my favorite number too!";
}
std::cout << "Nice try, but that's not my favorite number" << std::endl;
return 0;
}
答案 0 :(得分:3)
感谢弄清楚了!
#include <iostream>
int main()
{
int favorite_number;
bool completed = false;
while(completed == false)
{
std::cout << "Enter your favorite number between 1 and 100: ";
std::cin >> favorite_number;
if(favorite_number == 5 || favorite_number == 6 || favorite_number == 7)
{
std::cout << "Amazing!! That's my favorite number too!";
completed = true;
return 0;
}
else
std::cout << "Nice try, but that's not my favorite number" << std::endl;
}
return 0;
}
答案 1 :(得分:1)
很高兴您找到了解决方案!此外,请查看以下代码:
int main()
{
int favorite_number;
while(1)
{
std::cout << "Enter your favorite number between 1 and 100: ";
std::cin >> favorite_number;
if(5 == favorite_number || 6 == favorite_number || 7 == favorite_number)
{
std::cout << "Amazing!! That's my favorite number too!";
return 0;
}
else
std::cout << "Nice try, but that's not my favorite number" << std::endl;
}
}
您可以使循环无限,而无需使用已完成的bool。只要插入的号码与收藏夹号码之一不同,它就可以运行。此外,代码中的最后一个返回值是额外的。例如,在if(5 == favorite_number)
中更改顺序被认为是一种好习惯,因为您可能会错误地写出favorite_number = 5
(赋值),这是有效的,这样您将很难找到一个错误。>