布尔函数问题
Boolean function problems
我的布尔函数有问题。当我编译程序时一切正常,但是当我输入 "no" 时它仍然显示 "what can I help you with?".
#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);
}
你的逻辑是倒退的 - verification
returns false
对于任何不是 "yes"
的东西。由于 "no"
不是 "yes"
、verification("no")
returns false
,并且在 main
函数中如果 !verification("no")
,计算结果为 true
.
似乎您应该从 if
语句中删除 !
运算符。
当你输入 yes 时会发生什么?
发生的事情是,当您键入 no 时,它 returns 为 false。然后将其反转 (!) 为真。它工作正常,但你正在翻转它,所以它不仅适用于 "yes",它实际上适用于除“是”之外的所有内容。
删除! (不是运算符)它会按您预期的那样工作。
我的布尔函数有问题。当我编译程序时一切正常,但是当我输入 "no" 时它仍然显示 "what can I help you with?".
#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);
}
你的逻辑是倒退的 - verification
returns false
对于任何不是 "yes"
的东西。由于 "no"
不是 "yes"
、verification("no")
returns false
,并且在 main
函数中如果 !verification("no")
,计算结果为 true
.
似乎您应该从 if
语句中删除 !
运算符。
当你输入 yes 时会发生什么? 发生的事情是,当您键入 no 时,它 returns 为 false。然后将其反转 (!) 为真。它工作正常,但你正在翻转它,所以它不仅适用于 "yes",它实际上适用于除“是”之外的所有内容。
删除! (不是运算符)它会按您预期的那样工作。