我编写了此程序,但是它不起作用。
您输入两个数字。然后按+或-。如果按+,则应加上数字。如果按-应该减去。但是那部分不起作用。
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
char opt;
int a,b,s;
scanf("%d",&a);
scanf("%c\n",&opt);
scanf("%d",&b);
if(opt=='+') { //this part doesn't work
s=a+b;
}
else if(opt=='-') {
s=a-b;
}
printf("%d",s);
return 0;
}
我该怎么办?
scanf("%d",&a);
getchar();
只需从此行中删除\ n。scanf(“%c \ n”,&opt);所以会...scanf(“%c”,&opt);
[当使用转换说明符%c
时,scanf读取所有字符,包括空格。
使用以下电话
scanf( " %c", &opt );
^^^
请参见'%'
符号前的空白和缺少的'\n'
。