九度 OJ 题目1019:简单计算器

来源:互联网 发布:圣火明尊盾牌进阶数据 编辑:程序博客网 时间:2024/04/30 06:11
题目描述:
    读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。
输入:
    测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。
输出:
    对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。
样例输入:
1 + 24 + 2 * 5 - 7 / 110
样例输出:
3.0013.36
/*该题要特别注意输入格式*/#include <stdio.h>#include<stack>using namespace std;int main(){    stack<double> s;    char c1,c2;    int d;    //注意加一个空格对应数字之后的空格    while(scanf("%d ", &d)!=EOF && d!=0) {        s.push(d);        //%c %d%c 分别接受字符、字符后的空格、数字、字符。        //若判断最后一个字符不为空格,则说明输入结束        while( scanf("%c %d%c", &c1,&d,&c2)) {          if(c1 == '+') {            s.push(d);          }else if(c1 == '-'){            s.push(-d);          }else if(c1 == '*') {            double tmp = s.top() * d;            s.pop();            s.push(tmp);          }else if(c1 == '/') {            double tmp = double(s.top() / d);            s.pop();            s.push(tmp);          }            if(c2 != ' ') break;      //表达式输入结束        }        while(!s.empty()) {            if(s.size() == 1) {                double r = s.top();                s.pop();                printf("%.2lf\n", r);            }else {                double a,b,c;                a = s.top();                s.pop();                b = s.top();                s.pop();                c = a + b;                s.push(c);            }        }    }    return 0;}

0 0