使用用户输入('+'/'-')的C控制台程序,无法进行数学运算

问题描述 投票:-4回答:3

我编写了此程序,但是它不起作用。

您输入两个数字。然后按+或-。如果按+,则应加上数字。如果按-应该减去。但是那部分不起作用。

#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;
}

我该怎么办?

c if-statement scanf
3个回答
0
投票
scanf("%d",&a);
getchar();

-1
投票

只需从此行中删除\ n。scanf(“%c \ n”,&opt);所以会...scanf(“%c”,&opt);


-1
投票

[当使用转换说明符%c时,scanf读取所有字符,包括空格。

使用以下电话

scanf( " %c", &opt );
        ^^^ 

请参见'%'符号前的空白和缺少的'\n'

© www.soinside.com 2019 - 2024. All rights reserved.