如何检查变量是否等于多个值 [英] How to check if variable equal to multiple values
问题描述
在C中我想检查变量是否等于多个值,并且不完全分离也不知道如何编码.
In C I want to check if variable equal to multiple values and I don't know how to code it without separating it fully.
if(str [i] =='u'||'o'||'i'|| e'||'a')
始终使我为真,而我没有不明白为什么,我需要解释.
if (str[i]=='u'||'o'||'i'||'e'||'a')
giving me always true and I don't understand why, I need explanation.
if(str [i] ==('u'||'o'||'i'||'e'||'a'))
给我总是假,我不明白为什么,我需要解释.
if (str[i]==('u'||'o'||'i'||'e'||'a'))
giving me always false and I don't understand why, I need explanation.
谢谢.
推荐答案
不同的结果与运算符优先级有关.
The different results has to do with operator precedence.
x == y || z
与
(x == y) || z
与
x == (y || z)
您的表达式为'u'||'o'||'i'||'e'||'a'
,因此在我们的情况下为 y
将为'u'
和 z
为'o'||'i'||'e'||'a'
. z
的计算结果为true,因为至少一个操作数(在本例中为所有操作数)为非零.因此,第一行等效于(str [i] =='u')||1
当然会一直取值为1,这是正确的.另一方面, str [i] ==('u'|| 1)
与 str [i] == 1
相同,因为'u'||1
等于1.
You have the expression 'u'||'o'||'i'||'e'||'a'
so in our case, y
will be 'u'
and z
will be 'o'||'i'||'e'||'a'
. z
will evaluate to true, because at least one of the operands (all of them in this case) is non-zero. So the first line will be equivalent to (str[i] == 'u') || 1
which of course always will evaluate to 1, which is true. On the other hand, str[i] == ('u' || 1)
is the same as str[i] == 1
because 'u' || 1
will evaluate to 1.
在C语言中没有很好的内置方法来完成这样的事情.您可以做的,很容易概括的是编写这样的自定义函数:
There is no good built in way to do such a thing in C. What you could do, that is pretty easy to generalize is to write a custom function like this:
bool isMember(char e, char*s, size_t size)
{
for(size_t i; i<size; i++) {
if(s[i] == e)
return true;
}
return false;
}
上述功能很容易针对不同类型进行修改.但是在您的情况下,它可以像这样使用:
The above function is easy to modify for different types. But in your case it can be used like this:
char characters[] = {'u','o','i','e','a'};
if (isMember(str[i], characters, sizeof(characters)) {
在处理 char
时,有一些更简单的方法,但我选择此解决方案是因为它不仅限于 char
.
When dealing with char
there are somewhat easier methods, but I chose this solution because it is not restricted to char
.
这篇关于如何检查变量是否等于多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!