7-19 求前缀表达式的值(25 分)---栈的运用

算术表达式有前缀表示法、中缀表示法和后缀表示法等形式。前缀表达式指二元运算符位于两个运算数之前,例如2+3*(7-4)+8/4的前缀表达式是:+ + 2 * 3 - 7 4 / 8 4。请设计程序计算前缀表达式的结果值。

输入格式:

输入在一行内给出不超过30个字符的前缀表达式,只包含+-*\以及运算数,不同对象(运算数、运算符号)之间以空格分隔。

输出格式:

输出前缀表达式的运算结果,保留小数点后1位,或错误信息ERROR

输入样例:

+ + 2 * 3 - 7 4 / 8 4

输出样例:

13.0
#include<cstdio>
#include<cstring>
#include<string>
#include<string.h>
#include<cmath>
#include<algorithm>
#include<iostream>
#include<queue>
#include<stack>
#include<vector>
#define ll long long
using namespace std;

char s[100];

stack<double>ac;

bool op(char c){
    if(c=='+'||c=='-'||c=='*'||c=='/'){
        return 1;
    }
    else return 0;
}

int main(){
    while(gets(s)){
        while(!ac.empty()){
            ac.pop();
        }
        int len=strlen(s);
        int n=1;
        double num=0;
        int flag=0; //标记是否有0为除数的情况
        for(int i=len-1;i>=0;i--){
            if(s[i]>='0'&&s[i]<='9'){
                num+=(s[i]-'0')*n;
                n*=10;
            }
            else if(s[i]=='.'){  //小数
                num=num/(n*1.0);
                n=1;
            }
            else if((s[i]=='+'||s[i]=='-')&&num!=0){
                if(s[i]=='+'){
                    ac.push(num);
                    i--; //跳过下一个空格
                    continue;
                }
                else{
                    num=-num;
                    ac.push(num);
                    i--; //跳过下一个空格
                    continue;
                }
            }
            else if(s[i]==' '){ //其中一个运算数已经统计完
                ac.push(num);
                num=0;
                n=1;
                continue;
            }
            else if(op(s[i])){ //如果是运算符
                double a=ac.top();
                ac.pop();
                double b=ac.top();
                ac.pop();
                double t=0;
                if(s[i]=='+'){
                    t=a+b;
                }
                else if(s[i]=='-'){
                    t=a-b;
                }
                else if(s[i]=='*'){
                    t=a*b;
                }
                else if(s[i]=='/'){ //注意判断除数为零
                    if(b==0){
                        flag=1;
                        break;
                    }
                    t=a/b;
                }
                ac.push(t);
                i--; //跳过下一个空格
            }
        }
        if(flag==0){
            printf("%.1f\n",ac.top());
        }
        else{
            printf("ERROR\n");
        }
    }
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值