问题描述
我试图将一个字符串作为输入,如果它等于 X++ 或 ++X,我想计算它。为此,我编写了价值代码。尽管它对 X++ 工作正常,但对于 X-- 它不起作用。我该如何解决问题?
#include<stdio.h>
#include<string.h>
int main() {
int n,count=0;
char c[5];
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%s",c);
if(strcmp(c,"X++")==1 || strcmp(c,"++X")==1) count++;
else count--;
}
printf("%d",count);
return 0;
}
解决方法
您可能希望将 strcmp(c,"X++")==1
更改为 strcmp(c,"X++")==0
,并将 strcmp(c,"++X")==1
更改为 strcmp(c,"++X")==0
。如果 strcmp()
的参数相等,则返回 0
,而不是 1
。您可以阅读有关 strcmp()
here 的更多信息。