繁体   English   中英

似乎无法使我的IF语句正常工作

[英]Can't seem to get my IF statement to work properly

我似乎无法获得这些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;
}

这不正确:

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

它应该是

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

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

"N" != 0

这总是true"N"是一个字符串文字,永远不能为NULL

|| 运算符不会像您认为的那样工作。

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

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

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

您还应对"y""Y"进行类似的调整。

此部分未正确评估:

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

Shold是:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM