求前缀表达式的值——线性结构

进阶实验3-3.1 求前缀表达式的值 (25分)

求前缀表达式的值需要从后往前读,其他和后缀表达式求值方式相同,利用堆栈求值

输入样例

“ + + 2 * 3 - 7 4 / 8 ”

输出样例

13.0

运行结果在这里插入图片描述

代码

#include <iostream>
#include <iomanip>
#include <stack>
#include <cstring>
#include <cmath>
using namespace std;
stack<double> num;
bool flag=true;
double sum=0;
bool operation(char letter){
    int temp1,temp2;
    if(!num.empty()){
        temp1=num.top();
        num.pop();
    } else{
        cout<<"ERROR";
        return false;
    }
    if(!num.empty()){
        temp2=num.top();
        num.pop();
    } else{
        cout<<"ERROR";
        return false;
    }
    switch (letter){
        case '+':num.push(temp1 + temp2);
            break;
        case '-':num.push(temp1 - temp2);
            break;
        case '*':num.push(temp1 * temp2);
            break;
        case '/':if(temp2==0){
                cout<<"ERROR";
                return false;
            }
            else
                num.push(temp1 / (temp2*1.0));
            break;
    }
    return true;
}
int  main()
{
    char s[71];
    cin.getline(s,71);
    for (int i = strlen(s)-1; i >=0 ; --i) { //从后往前读
        string digitStr="";
        switch (s[i]){
            case '+':flag=operation(s[i]);
                break;
            case '-':flag=operation(s[i]);
                break;
            case '*':flag=operation(s[i]);
                break;
            case '/':flag=operation(s[i]);
                break;
        }
        if(s[i]<='9'&&s[i]>='0'){
            while(i>=0 && s[i]!=' ') //不要漏掉i>=0条件
            {
                digitStr=s[i]+digitStr;
                --i;
            } //读数
            //printf("atof:%f\n",atof(digitStr.c_str()));
            num.push(atof(digitStr.c_str()));
        }

    }
    if(flag){
        sum=num.top();
        cout << fixed << setprecision(1) << sum;
    }
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值