简单计算器

Description

读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。 
 

Input

测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。 
 

Output

对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。 
 

Sample Input

1 + 2 4 + 2 * 5 - 7 / 11 0
 

Sample Output

3.00 13.36
 
这道题可以用栈做,一个字符栈,一个数字栈,中缀表达式转化为后缀表达式即可
但是因为只有四种运算符号出现,所以可以采用简单的方法
可以先遍历一遍表达式,把乘除算出来,结果存到一个数组中,,加减的根据正负存到一个数组里面,最后把数组里的数字相加,
注意:数字和字符之间有个空格
    总的案例录入以0 结束
    每个案例以回车结束
 
#include <stdio.h>
int main()
{
    double num, a[205];
    while(scanf("%lf", &num) != EOF)
    {
        int len = 0;
        char ch = getchar();
        char c;
        if(num == 0 && ch == '
')
            break;
        else if(ch == '
')
        {
            printf("%.2lf
", num);
            continue;
        }
        a[len++] = num;
        while(scanf("%c%lf", &c, &num))
        {
            ch = getchar();
            switch(c)
            {
                case '+': a[len++] = num; break;
                case '-': a[len++] = -num; break;
                case '*': a[len-1] *= num; break;
                case '/': a[len-1] /= num;
            }
            if(ch == '
')
                break;
        }          
        double ans = 0;
        for(int i = 0; i < len; i++)
            ans += a[i];
        printf("%.2lf
", ans);            
    }
    return 0;
}
原文地址:https://www.cnblogs.com/rain-1/p/5042379.html