【问题标题】:Boolean function problems布尔函数问题
【发布时间】:2015-10-07 20:55:26
【问题描述】:

我的布尔函数有问题。当我编译程序时,一切运行良好,但当我输入“否”时,它仍然说“我能帮你什么?”。

#include <iostream>
#include <string> //size()
#include <cctype> //isdigit()
using namespace std; //(xxx)xxx-xxxx

bool verification(string yesOrno)
{
    if(yesOrno == "yes")return(true);
    else               return(false);
}

int main()
{
    string yesOrno;

    cout <<"Do you need more help\n";
    cin >> yesOrno;

    if(!verification(yesOrno))cout <<"What can I help you with?\n";

    return(0);
}

【问题讨论】:

  • 你能告诉我们!false是什么吗?
  • 附带说明,您可以通过使用return (yesOrno == "yes"); 来简化验证评估,而不是添加额外的步骤并使事情变得不必要。
  • @DrewDormann 答案是……true
  • 第 2 行和第 4 行的 cmets 很神秘
  • @MattMcNabb 我读到这意味着 “评论 2 和 4(对这个问题)是神秘的”,并且......花了很多时间来欣赏这样的元观察。

标签: c++ function if-statement boolean


【解决方案1】:

你的逻辑是倒退的——verification 返回false 任何不是"yes" 的东西。由于"no" 不是"yes"verification("no") 返回false,并且在main 函数中,如果!verification("no"),则打印出此消息,其计算结果为true

看来您应该从if 语句中删除! 运算符。

【讨论】:

    【解决方案2】:

    当您输入“是”时会发生什么? 发生的事情是当你输入 no 时,它返回 false。然后将其反转(!)为真。它工作正常,但你正在翻转它,所以它不仅适用于“是”,它实际上适用于除“是”之外的所有东西。

    删除 ! (不是操作员),它将按您的预期工作。

    【讨论】:

      猜你喜欢
      • 2018-09-25
      • 2011-08-06
      • 2022-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-27
      • 1970-01-01
      相关资源
      最近更新 更多