题目1019:简单计算器

时间限制:1秒
内存限制:32 兆
特殊判题:
提交:3688
解决:1369



 
题目描述:

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

输入:

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

输出:

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

样例输入:
1 + 2
4 + 2 * 5 - 7 / 11
0
样例输出:
3.00
13.36
998
 

经典的栈的应用:

#include<stdio.h>
#include<stack>
#include<string.h>
using namespace std;
stack<char> op;
stack<double> num;
int priority(char c)
{
    switch (c)
    {
        case '?': 
            return 0;
        case '+':
            return 1;
        case '-':
            return 1;
        case '*':
            return 2;
        case '/':
            return 2;
    }
    return -1;
}
double count(char c)
{
    double i=0,j=0;
    switch (c)
    {
        case '+':
            i=num.top();
            num.pop();
            j=num.top();
            num.pop();
            return i+j;
        case '-':
            i=num.top();
            num.pop();
            j=num.top();
            num.pop();
            return j-i;
        case '*':
            i=num.top();
            num.pop();
            j=num.top();
            num.pop();
            return i*j;
        case '/':
            i=num.top();
            num.pop();
            j=num.top();
            num.pop();
            return j/i;
    }
    return -1;
}
int main()
{
    char str[300];
    while(gets(str))//gets()当为输入的文件尾时返回0
    {
        if (str[0]=='0' || strlen(str)==1) break;
        while(!op.empty()) op.pop();
        while(!num.empty()) num.pop();
        char strs[300]="?\0";
        strcat(str,"?");//strcat()也是编辑字符串的有用函数
        strcat(strs,str);
        int l=strlen(strs);
        op.push('?');
        for (int i=1;i<l;i++)
        {
            switch(strs[i])
            {
                case ' ':
                    break;
                case '?': //罕见的使用方法
                case '+':
                case '-':
                case '*':
                case '/':
                    if (priority(op.top())<priority(strs[i]))
                    {
                        op.push(strs[i]);
                    }
                    else
                    {
                        while(priority(op.top())>=priority(strs[i]) && op.top()!='?')  
                        {
                            num.push(count(op.top()));
                            op.pop();
                        }
                        op.push(strs[i]);
                    }
                    break;
                default:
                    int k=0;
                    while(strs[i]>='0' && strs[i]<='9')
                    {
                        k=k*10+(int)(strs[i]-'0');
                        i++;
                    }
                    i--;
                    num.push(k);
                    break;
            }
        }
        printf("%.2f\n",num.top());
    }
    return 0;
}

 

posted on 2014-03-13 10:01  武晓伟  阅读(166)  评论(0编辑  收藏  举报