模拟简单运算器的工作。假设计算器只能进行加减乘除运算,运算数和结果都是整数,四种运算符的优先级相同,按从左到右的顺序计算。
输入格式:
输入在一行中给出一个四则运算算式,没有空格,且至少有一个操作数。遇等号”=”说明输入结束。
输出格式:
在一行中输出算式的运算结果,或者如果除法分母为0或有非法运算符,则输出错误信息“ERROR”。
输入样例:
1+2*10-10/2=
输出样例:
10
思路:
1、按int读取数字,按char读取运算符,循环读取,到‘=’停止;
2、利用switch-case盒跳转到特定四则运算;
3、利用error这个错误标识来记录算式是否合法(避免在switch里面直接printf造成多个出口);
4、输出时首先判定是否合法,如果合法输出运算结果
代码如下:
#include <stdio.h>
int main ()
{
int n; //操作数
char operator; //运算符
int output; //运算结果
int error=0; //错误标记
//读第一个数
scanf ("%d", &n);
output = n;
//读第一个运算符
scanf ("%c", &operator);
//循环读取
while (operator!='=')
{
//读下一个数
scanf ("%d", &n);
//四则运算
switch (operator)
{
case '+':
output = output+n;
break;
case '-':
output = output-n;
break;
case '*':
output = output*n;
break;
case '/':
if (n==0)
//分母为0非法判定
{
error = 1;
break;
}
output = output/n;
break;
default:
error = 1;
break;
}
//读下一个运算符
scanf ("%c", &operator);
}
//输出
if (error==1)
//非法判定
{
printf("ERROR\n");
}
else
//正常输出运算结果
{
printf("%d", output);
}
}
1万+

被折叠的 条评论
为什么被折叠?



