06-1. 简单计算器(20)

模拟简单运算器的工作。假设计算器只能进行加减乘除运算,运算数和结果都是整数,4种运算符的优先级相同,按从左到右的顺序计算。

输入格式:

输入在一行中给出一个四则运算算式,没有空格,且至少有一个操作数。遇等号”=”说明输入结束。

输出格式:

在一行中输出算式的运算结果,或者如果除法分母为0或有非法运算符,则输出错误信息“ERROR”。

输入样例:

1+2*10-10/2=

输出样例:

10

 

 

 

 1 #include <stdio.h>
 2 
 3 int main()
 4 {
 5     int x, flag = 0;
 6     int result;
 7     char ch = '1';
 8     scanf("%d", &result);
 9     
10     while(ch != '=') {
11         scanf("%c", &ch);
12         if(ch == '=') 
13             break;
14         scanf("%d", &x);
15         if(ch == '+') {
16             result += x;
17         }
18         else if(ch == '-') {
19             result -= x;
20         }
21         else if(ch == '*') {
22             result *= x;
23         }
24         else if(ch == '/') {
25             if(x != 0) {
26                 result /= x;
27             }
28             else 
29                 flag = 1;
30         }
31         else 
32             flag = 1;
33     }
34     if(flag) {
35         printf("ERROR");
36     }
37     else 
38         printf("%d\n", result);
39         
40     return 0;
41 }

 

posted @ 2014-07-29 22:50  Acalm  阅读(2170)  评论(3编辑  收藏  举报