简体   繁体   English

C 控制台程序使用用户输入(“+”/“-”)进行数学运算不起作用

[英]C Console Program using User Input ('+' / '-') for Mathematical operations not functioning

I made this program but it doesn't work.我做了这个程序,但它不起作用。

You enter two numbers.您输入两个数字。 Then you press + or -.然后按 + 或 -。 If you press + it should add the numbers.如果您按 + 它应该添加数字。 If you press - it should subtract.如果你按 - 它应该减去。 But that part doesn't work.但那部分不起作用。

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

What should I do?我应该怎么办?

scanf("%d",&a);
getchar();

Just remove \n from this line.. scanf("%c\n",&opt);只需从这一行中删除 \n .. scanf("%c\n",&opt); So it will be... scanf("%c",&opt);所以它将是... scanf("%c",&opt);

When you are using the conversion specifier %c then scanf reads all characters including white spaces.当您使用转换说明符%c时,scanf 会读取所有字符,包括空格。

Use the following call使用以下调用

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

See the blank before the '%' symbol and the absent symbol '\n' .请参阅'%'符号之前的空白和不存在的符号'\n'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM