为什么我的c!='o'|| c!='x'条件总是如此?

Jas*_*Kim 0 logical-operators conditional-statements logical-or

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

while (c != 'o' || c != 'x') {
    c = getANewValue();
}
Run Code Online (Sandbox Code Playgroud)

我想让它一直运行,直到我得到一个'o''x',但它永远不会退出,即使c'o''x'.为什么不?

我也尝试过使用if:

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

但这也总是显示错误信息,即使c'o''x'.为什么?

T.J*_*der 11

这种情况(c != 'o' || c != 'x')永远不会是假的.如果c'o',则为c != 'x'真,并满足OR条件.如果c'x',则为c != 'o'真,并满足OR条件.

你想要&&(AND),而不是||(OR):

while (c != 'o' && c != 'x') {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

"虽然c不是'o'c不是''x'......"(例如,它们都不是).

或者使用De Morgan的法律,包括:

while (!(c == 'o' || c == 'x')) {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

"虽然这是不正确的(c'o'c'x')......"