2

我似乎无法让这些 if 语句按预期工作。无论我输入“字符串答案”什么,它总是跳到第一个 IF 语句,其中条件设置为仅在答案正好是“n”或“N”或答案正好是“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;
}
4

3 回答 3

9

这是不正确的:

if (answer == ("n") || ("N"))

它应该是

if (answer == "n" || answer == "N")

找出当前代码编译的原因是有益的:在 C++ 和 C 中,隐式!= 0添加到不代表布尔表达式的条件。因此,你表达的第二部分变成

"N" != 0

永远是true:"N"是一个字符串文字,永远不可能是NULL.

于 2013-11-11T19:19:21.937 回答
5

操作员的||工作方式并不像您认为的那样。

if (answer == ("n") || ("N"))

正在检查是否answer"n",如果不是,则将其评估"N"为布尔值,在这种情况下始终为真。你真正想做的是

if (answer == ("n") || answer == ("N"))

您还应该针对"y"和的检查进行类似的调整"Y"

于 2013-11-11T19:20:12.900 回答
2

这部分没有正确评估:

if (answer == ("n") || ("N")) {}

应为:

if (answer == "n" || answer == "N") {}
于 2013-11-11T19:19:58.400 回答