2012-07-26 24 views
0

下面的C++代码:如果声明没有工作,我怎么想

if (a != '0.5' || a != '0.6') 
{ 
    cout << "The answer is neither 0.5 nor 0.6 " << '\n'; 
} 

我也曾尝试

if ((a != '0.5') || (a != '0.6')) 
{ 
    cout << "The answer is neither 0.5 nor 0.6 " << '\n'; 
} 

,并试图

if (!(a== '0.5') || !(a==0.6) 
{ 
    cout << "The answer is neither 0.5 nor 0.6 " << '\n'; 
} 

从用户接收的数并检查数字是0.5还是0.6;如果是的话,它应该作为虚假陈述执行,但如果它是任何其他数字,它应该执行为真。但是,它始终保持为true,但当输入0.5或0.6时它应该作为false执行。这是不同的,当我使用一个else if语句在它正常工作是:

if (a != 0.5) 
{ 
    //what to do if true. 
} 
else if (a != 0.6) 
{ 
    //What to do if this is true and the first id wrong. 
} 
else 
{ 
    //What to do if none are true. 
} 

为什么不能在= if语句执行呢?

+0

好吧,我不是故意的代码最终看起来像。 – urbanslug 2012-07-26 08:14:11

+0

好吧,如何使用if(a!='x'|| a!='y'){}语句就是我想知道的。没有其他的请 – urbanslug 2012-07-26 08:15:40

回答

0

删除0.5和0.6的单引号,你应该使用& &(AND)不||(OR),即: if (a != 0.5 && a != 0.6)

0

它必须是

if (a != 0.5 && a != 0.6) 
+1

为什么当'0.5'和'0.6'显然是错误的时候这会得到upvoted ... – Marlon 2012-07-26 08:23:07

2

一个应该是浮动还是字符串?无论哪种方式,这个语法都是错误的'0.5',如果它是一个字符串使用双引号。不要与浮点数/双精度浮点数进行比较,因为内部表示形式不会像您期望的那样工作,请参阅how-to-correctly-and-standardly-compare-floats

+0

我先试了一下,没有引号,它失败了。 – urbanslug 2012-07-26 08:27:04

+0

@MosesMwaniki,但它应该是一个浮点数或字符串文字? – juanchopanza 2012-07-26 08:30:59

3

逻辑错误。您目前正在检查一个数字是否同时不是0.5或不是0.6;所有数字都会通过该测试。您需要用逻辑或(&&)替换逻辑或(||)。

此外,您需要从数字中删除单引号,否则您正在创建具有实现定义值的多字符文字。

if (a != 0.5 && a != 0.6) 
{ 
    cout << "The answer is neither 0.5 nor 0.6 " << '\n'; 
} 
0

如果a是一个字符,然后当你的财产以后类似奇怪的事情会发生:

char a = '0.5'; 
cout << "A: " a << endl; 

这将输出(在我的编译器,不能确保任何其他人):

A: 5 

和:

char a = '0.5'; 
if (a == '5') 
    cout << "yey" << endl; 
else 
    cout << "oops" << endl; 

这将输出:

yey 

但我认为这种行为是不确定的(我不知道是肯定的)。无论如何,它不会做你认为它会的事情。

其次,我认为你的逻辑是错的:

你是在说:

如果没有0.5与否0.6

在哪里,我认为你的意思是

如果没有0.5,而不是0.6

if (a != '0.5' && a != '0.6') 
1

什么是a

的std :: string

假设:

std::string a; 
std::cin >> a; 

然后下面的代码工作:

if (a == "0.5" || a == "0.6") 
{ 
    // Do something when it's true 
} 
else 
{ 
    // Do something when it's false 
} 

虽然 “0.5” 和 “0.6” 是为const char *,他们将转换为std :: string,所以它运作良好。

为const char *

char a[BUFSIZE]; 
std::cin >> a; 
if (strcmp(a, "0.5") == 0 || strcmp(a, "0.6") == 0) 
{ 
    // Do something when it's true 
} 
else 
{ 
    // Do something when it's false 
} 

你可以使用STRCMP比较C风格字符串

浮点/双精度

当你在比较的花车,你可能会遇到的问题的精度。你可以编写一些函数或Float类来解决这个问题。就像这样:

const double EPS = 1e-8; 
inline bool FloatEqual(const double lhs, const double rhs) 
{ return std::fabs(rhs-lhs) <= EPS; } 
int main() 
{ 
    double a; 
    std::cin >> a; 
    if (FloatEqual(a, 0.5) || FloatEqual(a, 0.6)) 
    { 
    // Do something when it's true 
    } 
    else 
    { 
    // Do something when it's false 
    } 
} 

顺便说

这是有趣的发现,下面的语句是相等的

if (a == "0.5" || a == "0.6") 
if (!(a != "0.5" && a != "0.6"))