ç逻辑或如果 [英] C logical or in if
问题描述
我知道我不是在C非常好,但我认为,我可以得到这个权利:
I know I'm not very good in C but I thought that I could get this right:
if(strlen(type) == 0 || strcmp(type,"in")!=0 || strcmp(type,"out")!=0)
键入
来作为的char *
和我测试过这个code。与第一部分在condition.It工作well.If我具备的条件的第二部分,我的键入
包含中的
这是OK,但如果所有这三个条件都可以,如果我输入走出去
中,如果不是skipped.Why的是什么?
type
comes as a char*
and I've tested this code with the first part of the condition.It works well.If I have the second part of the condition and my type
contains "in"
it's ok but if all three conditions are available,if i input "out"
,the if isn't skipped.Why's that?
推荐答案
您code:
if(strlen(type) == 0 || strcmp(type,"in")!=0 || strcmp(type,"out")!=0){
" your code-1"
}
else{
" your code-2"
}
等同于:
if(strlen(type) == 0 ){
" your code-1"
}
else{
if(strcmp(type,"in")!=0){
" your code-1"
}
else{
if(strcmp(type,"out")!=0){
" your code-1"
}
else{
" your code-2"
}
}
}
的一点是,如果你有第一个的如果()
执行,如果字符串键入
有东西,那么其他人永远不会执行。因为一个空字符串(中的其他部分的)不能等同于中的
或出
。所以,你总是有选择执行code-1,如果字符串的不为空的和无关的执行,如果字符串是空的(即长度= 0 的)。
Point is if you have first if()
executes if string type
have something, then else never executes. Because a empty string(in else part) can't be equals to "in"
or "out"
. So you always have choice to execute "code-1" if string is not empty and nothing to executes if string is empty (that is length = 0).
编辑:
我觉得你想要的东西一样,如果键入
字符串为中,然后执行code-1,如果类型是走出去,然后执行第二个code-2。这样的:
I think you wants something like if type
string is "in" then execute "code-1" if type is "out" then execute second code-2. like:
if(strlen(type) == 0 ){
}
else{
if(strcmp(type,"in")!=0){
" your code-1"
}
else{
if(strcmp(type,"out")!=0){
" your code-2"
}
}
}
你可以这样做:
flag = 'o';// this will save string comparison again
if(strlen(type) == 0 || strcmp(type,"in")==0 ||
strcmp(type,"out")!=0 && !(flag='?')){
"code-1"
}
else{
if(flag=='o'){ //no strcmp needed
"code-2"
}
}
我在这里公布了code 根据我的逻辑,它为运行:
Here I posted a Code based on my logic and it run as:
:~$ ./a.out
Enter string: in
in
:~$ ./a.out
Enter string: out
out
:~$ ./a.out
Enter string: xx
:~$
这篇关于ç逻辑或如果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!