为什么我的 c != 'o' ||c != 'x' 条件总是正确的? [英] Why is my c != 'o' || c != 'x' condition always true?
问题描述
我有这个循环语句,我将使用类似 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
运算符,则布尔表达式将始终为真.
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屋!