【问题标题】:Can't seem to get my IF statement to work properly似乎无法让我的 IF 语句正常工作
【发布时间】:2013-11-23 17:03:56
【问题描述】:

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

【问题讨论】:

    标签: c++ if-statement conditional-statements conditional-operator


    【解决方案1】:

    这是不正确的:

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

    应该是

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

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

    "N" != 0
    

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

    【讨论】:

      【解决方案2】:

      || 操作符不像你想象的那样工作。

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

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

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

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

      【讨论】:

        【解决方案3】:

        这部分评估不正确:

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

        应该是:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-04-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-07-23
          • 2015-09-27
          相关资源
          最近更新 更多