gpt4 book ai didi

C逻辑或如果

转载 作者:太空宇宙 更新时间:2023-11-04 02:57:26 25 4
gpt4 key购买 nike

我知道我的 C 语言不是很好,但我认为我可以做对:

if(strlen(type) == 0 || strcmp(type,"in")!=0 || strcmp(type,"out")!=0)

typechar* 的形式出现,我已经用条件的第一部分测试了这段代码。效果很好。如果我有第二部分条件和我的 type 包含 "in" 没关系,但是如果所有三个条件都可用,如果我输入 "out",则如果是' t skipped.Why's that?

最佳答案

你的代码:

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"
}
}
}

要点是如果你有 first if() 如果字符串 type 有内容,则执行,否则永远不会执行。因为空字符串(in else part) 不能等于"in""out"。因此,如果字符串不为空,您始终可以选择执行“code-1”,如果字符串为空(即长度 = 0),则不执行任何操作。

编辑:

我想你想要这样的东西,如果 type string is "in"then execute "code-1"if type is "out"then execute second code-2。喜欢:

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"
}
}

Here I posted a Code根据我的逻辑,它运行为:

:~$ ./a.out 
Enter string: in
in
:~$ ./a.out
Enter string: out
out
:~$ ./a.out
Enter string: xx
:~$

关于C逻辑或如果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15885715/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com