IF statement with logical OR [duplicate]

北城余情 提交于 2020-01-22 02:22:07

问题


if(1 == 2 || 4)
{
cout<<"True";
}
else
{
cout<<"False";
}

This is how I read the above. If 1 is equal to 2 or 4, then print true. Otherwise, print false. When this is executed though... true is printed. Obviously I'm misunderstanding something here. 1 is not equal to 2 or 4. Wouldn't that make it false?


回答1:


Yeah, I've made the same mistake.

Read the sentence again:

If 1 is equal to 2 or 4, then print true.

The "2" and "4" both refer to the "If 1 is equal to [...]." That means, the sentence is just an abbreviation of

If 1 is equal to 2 or 1 is equal to 4, then print true.

This leads us to the if-clause

if (1 == 2 || 1 == 4)

instead.


1 == 2 || 4 is true because (1 == 2) == false ORed with 4 == true, yields true (false OR true = true).




回答2:


This is how I read the above. If 1 is equal to 2 or 4, then print true. Otherwise, print false. When this is executed though... true is printed. Obviously I'm misunderstanding something here. 1 is not equal to 2 or 4. Wouldn't that make it false?

No, 1 is equal to 2 or 4. 4 is true (because it's not zero). So anything "or 4" is also true. Therefore "1 is equal to 2 or 4" is true.




回答3:


It's evaluating to true because if you check for the boolean value of just an integer (like you're doing with the number 4), it will evaluate to true. Like the people said above, you have to split it up.




回答4:


This not how if statements work in C++. If you want to know if something is equal to one thing or another thing then it is

if (this == this_thing || this == another_thing)

What you have

if(1 == 2 || 4)

Gets evaluated to

if ((1 == 2) || 4)
if (false || true)
if (true)

So the if statement will always be true.




回答5:


In this your phrase

If 1 is equal to 2 or 4, then print true

you need to add a pair of words that to get a correct equivalent C++ phrase

If 1 is equal to 2 or is equal to 4, then print true

Thus it will look the following way

if ( 1 == 2 or 1 == 4 )
{
    cout << "True";
}
else
{
    cout<<"False";
}

As for the original condition

1 == 2 || 4

then the compiler consideres it the following way (due to the priorities of the operators):

( 1 == 2 ) || 4

According to the C++ Stanbdard

The operators == and != both yield true or false, i.e., a result of type bool.

So as 1 == 2 is equal to false then you get

false || 4

where 4 as it is not equal to 0 is converted to boolean true and as result the entire condition evaluates to true



来源:https://stackoverflow.com/questions/33422793/if-statement-with-logical-or

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!