if statement not working right?

2020-01-29 02:44发布

I've looked and looked with the debugger and cannot seem to figure out why the IF statement always prints the message.

The IF statement checks to see if yesno != 'Y' ||(or) 'N' but regardless if i type y or Y or n N or H B it will show... . Im not sure what move to make anymore! I cant seem to find where its going wrong?

if(yesno != 'Y' || 'N') { ...

Thanks guys.

5条回答
太酷不给撩
2楼-- · 2020-01-29 03:28

The || doesn't quite mean what you think it means. The correct approach is:

if (yesno != 'Y' && yesno != 'N') { ...

This evaluates each side of the && independently, and the result is true if both sides are true.

Note that

if (yesno != 'Y' || yesno != 'N') { ...

will always be true because any given character is either not Y or it is not N. This is probably not what you want.

查看更多
相关推荐>>
3楼-- · 2020-01-29 03:29

You need to put

if (yesno != 'Y' || yesno != 'N')

You always need to put the full expression twice.

查看更多
家丑人穷心不美
4楼-- · 2020-01-29 03:31

you cannot OR an expression (yesno!='Y') and a statement ("N") which is also an expression. its only two or more expressions that can be combined using || and && to get the required output.

if(yesno!="Y"||"N")

is actually

if(yesno!="Y" || TRUE)

which is always true because:

Exp||TRUE=TRUE 

regardless of the expression.

use if(yesno!="Y"|| yesno!="N")      // and in this case its && and not || i think
查看更多
做自己的国王
5楼-- · 2020-01-29 03:38
if(yesno != 'Y' || 'N')

should be:

if(yesno != 'Y' && yesno != 'N')

You are chaining them which is incorrect. I am fairly sure you know that you should not and that is a typo, because you used && correctly on line no 44.

查看更多
甜甜的少女心
6楼-- · 2020-01-29 03:43

Take the conditional yesno != 'Y' || 'N' apart. It has two clauses:

  1. yesno != 'Y'. This is probably a comparison you intended; it checks to see if the char yesno is inequal to the value 'Y'.
  2. 'N'. This clause evaluates simply to the value 'N'. As a bool, 'N', which is not zero, is considered "true."

So you have "(stuff) || (always true)". Here "stuff" is yesno != 'Y' and "always true" is 'N'. The result will always be true.

查看更多
登录 后发表回答