#include <iostream>
#include <string>
using namespace std;
int main() {
string hint, play;
int max = 100, min = 0, tries=0, num;
bool again;
again = true;
while(again = true){
num = (max + min) / 2;
cout<< "The computer's guess is: " << num << endl;
cout << "Is your number higher, lower, or correct?: ";
cin >> hint;
if(hint !="lower"){
if(hint != "higher"){
if(hint!="correct"){
cout << "Is your number higher, lower, or correct?: ";
cin >> hint;
tries++;
if (hint == "higher")
min = num + 1;
else if (hint == "lower")
max = num - 1;
cout << "The computer's guess was correct after " << tries<<endl;
}while(hint != "correct");
cout << "do you want to play again?(y/n): ";
cin>>play;
if(play!="y"){
if(play!="n"){
cout << "do you want to play again?(y/n): ";
cin>>play;
if(play == "y"){
again = true;
if(play == "n"){
cout<<"thank you for playing";
break;
}
我还将行
while (again = true)
更改为
while (again)
。使用
=
运算符将
again
的值设置为
true
,我认为这是无意的。
==
操作符可能就是你要找的东西。但是,在任何if语句或循环中都没有必要检查
true
是否相等,因为如果条件等于true,则循环将始终运行。
while (again) {
num = (max + min) / 2;
cout << "The computer's guess is: " << num << endl; \
bool invalidInput = true;
while (invalidInput) {
cout << "Is your number higher, lower, or correct?: ";
cin >> hint;
// Remove whitespace and convert hint to lowercase
hint.erase(remove_if(hint.begin(), hint.end(), isspace), hint.end());
transform(hint.begin(), hint.end(), hint.begin(), [](unsigned char c) { return tolower(c); });
// Validate the input
if (hint == "higher" || hint == "lower" || hint == "correct") {