我似乎无法将这些if语句按预期工作。 无论我输入“字符串答案”,它总是跳转到第一个IF语句,其中条件设置为仅在答案正好为“n”或“N”时执行块或者答案恰好为“y”的块或“Y”。如果您输入任何其他内容,则应返回0。
// Game Recap function, adds/subtracts player total, checks for deposit total and ask for another round
int gameRecap() {
string answer;
answer.clear();
cout << endl << "---------------" << endl;
cout << "The winner of this Game is: " << winner << endl;
cout << "Player 1 now has a total deposit of: " << deposit << " credits remaining!" << endl;
cout << "-------------------------" << endl;
if (deposit < 100) {
cout << "You have no remaining credits to play with" << endl << "Program will now end" << endl;
return 0;
}
else if (deposit >= 100) {
cout << "Would you like to play another game? Y/N" << endl;
cin >> answer;
if (answer == ("n") || ("N")) {
cout << "You chose no" << endl;
return 0;
}
else if (answer == ("y") || ("Y")) {
cout << "You chose YES" << endl;
currentGame();
}
else {
return 0;
}
return 0;
}
else {
return 0;
}
return 0;
}
答案 0 :(得分:9)
这是不正确的:
if (answer == ("n") || ("N"))
应该是
if (answer == "n" || answer == "N")
找出当前代码编译的原因是有益的:在C ++和C中,隐式!= 0
被添加到不表示布尔表达式的条件中。因此,表达式的第二部分变为
"N" != 0
总是true
:"N"
是一个字符串文字,永远不会是NULL
。
答案 1 :(得分:5)
||
运算符不会像您认为的那样工作。
if (answer == ("n") || ("N"))
正在检查answer
是否为"n"
,如果不是,则将"N"
评估为布尔值,在这种情况下始终为真。你真正想做的是
if (answer == ("n") || answer == ("N"))
您还应针对"y"
和"Y"
进行类似的调整。
答案 2 :(得分:2)
此部分未正确评估:
if (answer == ("n") || ("N")) {}
Shold be:
if (answer == "n" || answer == "N") {}