我编写了这个程序来计算像“2 + 6 - 9”这样的表达式(数字和运算符之间有空格),但最后一个 if block 不正确。如何在收到\n 时中断循环,如果没有则存储输入。
#include <stdio.h>
#include<stdlib.h>
void main()
{
char oper;
int sum,y;
scanf("%d %c",&sum,&oper);
while(1)
{
scanf("%d",&y);
if(oper=='+')
sum += y;
else if(oper=='-')
sum -= y;
else if(oper=='/')
sum /= y;
else if(oper=='*')
sum += y;
if((scanf("%c",&oper))=='\n')
break;
}
printf("\n =%d",sum);
}
最佳答案
On success, the function returns the number of items of the argument list successfully filled.
替换这部分:
if((scanf("%c",&oper))=='\n')
break;
与:
if(scanf("%c",&oper) && oper=='\n')
break;
这个:
- 检查
scanf()
是否已将任何值放入oper
- 如果是,则检查该值是否等于
\n
关于计算表达式的c程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47969074/