为什么我的 c != 'o' ||c != 'x' 条件总是正确的? [英] Why is my c != 'o' || c != 'x' condition always true?

查看:12
本文介绍了为什么我的 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 运算符,则布尔表达式将始终为真.

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天全站免登陆