为什么我的c!='o'|| c!='x'条件始终为真吗? [英] Why is my c != 'o' || c != 'x' condition always true?

查看:135
本文介绍了为什么我的c!='o'|| c!='x'条件始终为真吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个循环语句,我将使用类似于C的语法(C,C ++,Java,JavaScript,PHP等都使用类似的语法)来表达:

I have this loop statement, which I'll express using C-like syntax (C, C++, Java, JavaScript, PHP, etc. all use similar syntax):

while (c != 'o' || c != 'x') {
    c = getANewValue();
}

我希望它运行直到得到'o''x',但是即使c'o''x',它也不会退出.为什么不呢?

I want it to run until I get a 'o' or 'x', but it never exits, even when c is 'o' or 'x'. Why not?

我也尝试过使用if:

if (c != 'o' || c != 'x') {
    // Show an error saying it must be either 'o' or 'x'
}

,但是即使c'o''x',它也始终显示错误消息.为什么?

but that also always shows the error message, even when c is 'o' or 'x'. Why?

推荐答案

必须为if(c!='o' && c!='x')而不是if(c!='o' || c!='x').如果使用or运算符,则布尔表达式将始终为true.

It must be if(c!='o' && c!='x') instead of if(c!='o' || c!='x'). If you use the or operator the boolean expression will be always true.

这篇关于为什么我的c!='o'|| c!='x'条件始终为真吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆