简单计算器-逆波兰式

C - 简单计算器
Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u

Description

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

Input

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

Output

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

Sample Input

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

Sample Output

       
       
3.00 13.36
 
/*
Author: 2486
Memory: 1748 KB		Time: 140 MS
Language: G++		Result: Accepted
Public:		No Yes
*/
//中缀转前缀进行求解
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <string>
#include <sstream>
#include <iostream>
#include <stack>
using namespace std;
string str;
int getrange(char x) {
    if(x=='-'||x=='+')return 1;
    return 2;
}
double getresult(string str) {
    stringstream cins(str);
    stack<string>sk;
    stack<double>B;
    string s;
    while(cins>>s) {
        sk.push(s);//从右到左,先压栈,然后弹出得到的就是从右到左的结果
    }
    while(!sk.empty()) {
        string n1=sk.top();
        sk.pop();
        if(isdigit(n1[0])) {
            B.push(atof(n1.c_str()));
        } else {
            char k=n1[0];
            double x=B.top();
            B.pop();
            double y=B.top();
            B.pop();
            if(k=='-')B.push(x-y);
            else if(k=='+')B.push(x+y);
            else if(k=='*')B.push(x*y);
            else B.push(x/y);
        }
    }
    return B.top();
}
int main() {
    while(getline(cin,str)) {
        if(str.length()<1)continue;
        if(str.length()==1&&str[0]=='0') {
            break;
        }
        string s;
        stack<string>A;
        stack<char>B;
        reverse(str.begin(),str.end());//从右到左
        stringstream cis(str);
        string str2;
        while(cis>>s) {
            if(isdigit(s[0])) {
                str2=str2+" "+s;
            } else {
                if(B.empty()||getrange(s[0])>=getrange(B.top())) {//运算等级比栈里面的高或者相等的话,就将它压栈
                    B.push(s[0]);
                    continue;
                }
                do {
                    char skd[2];
                    skd[0]=B.top();
                    skd[1]='\0';
                    string sk(skd);
                    B.pop();
                    str2=str2+" "+sk;
                } while(!B.empty()&&getrange(s[0])<getrange(B.top()));//否则进行弹出
                B.push(s[0]);
            }
        }
        do {
            char skd[2];
            skd[0]=B.top();
            skd[1]='\0';
            string sk(skd);
            B.pop();
            str2=str2+" "+sk;
        } while(!B.empty());
        reverse(str2.begin(),str2.end());
        printf("%.2lf\n",getresult(str2));
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值