题目1019:简单计算器

来源:互联网 发布:知远防务薪水 编辑:程序博客网 时间:2024/05/16 05:11
题目描述:
    读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。
输入:
    测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。
输出:
    对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。
样例输入:
1 + 24 + 2 * 5 - 7 / 110
样例输出:
3.0013.36

代码:

#include <stdio.h>#include <stack>using namespace std;stack<int> op;stack<double> in;char str[220];int p[][5] = {    1,0,0,0,0,    1,0,0,0,0,    1,0,0,0,0,    1,1,1,0,0,    1,1,1,0,0,};void getOp(bool &retop, int &retnum, int &i) {    if(i==0 && op.empty()==true) {        retop = true;        retnum = 0;        return;    }    if(str[i]==0) {        retop = true;        retnum = 0;        return;    }    if(str[i]>='0' && str[i]<='9')         retop = false;    else {        retop = true;        if(str[i]=='+')            retnum = 1;        else if(str[i] == '-')            retnum = 2;        else if(str[i] == '*')            retnum = 3;        else            retnum = 4;        i += 2;        return;    }    retnum = 0;    for(;str[i]!=' '&&str[i]!=0;i++) {        retnum *= 10;        retnum += str[i] - '0';    }    if(str[i]==' ')        i++;    return;}int main() {        while(gets(str)) {        if(str[0]=='0' && str[1]==0)            break;        bool retop;    int retnum;    int index=0;        while(!in.empty()) in.pop();        while(!op.empty()) op.pop();        while(true) {            getOp(retop,retnum,index);            if(retop == false)                in.push((double)retnum);            else {                double tmp;                if(op.empty() || p[retnum][op.top()]==1)                    op.push(retnum);                else {                    while(p[retnum][op.top()]==0) {                                                int ret = op.top();                        op.pop();                        double b = in.top();                        in.pop();                        double a = in.top();                        in.pop();                        if(ret==1)                            tmp = a + b;                        else if(ret==2)                            tmp = a - b;                        else if(ret==3)                            tmp = a * b;                        else if(ret==4)                            tmp = a / b;                        in.push(tmp);                    }                    op.push(retnum);                }            }                if(op.size()==2 && op.top()==0)                    break;        }        printf("%.2f\n",in.top());    }    return 0;}

1.创建2个栈,一个用于保存数字,一个用于保存操作符所对应的数字。'+', '-', '*', '/'分别代表1,2,3,4。在输入的表达式的收尾填充优先级最低的,分别用数字0,5表示。

2.创建二维数组,存储优先级。收尾优先级最低,'*','/'优先级高于'+','-'。 p[a][b]==1表示,a的优先级大于b,a入栈。若p[a][b]==0,则弹出操作符栈顶元素,从操作数栈弹出2个数,进行计算,再将结果入栈,重复上述步骤。

3.判断是否为数字。 str[i]>='0' && str[i]<='9'。 将数字字符转化为数字: str[i] - '0'


原创粉丝点击