C/C++语言实现利用栈计算前缀表达式的值

在考研复习过程中,我发现严书上给出的代码非常不易于理解,并且搜索引擎搜到的一些博客所写的代码实在是一言难尽。所以在此更新一些根据我自己的理解写的代码,希望可以帮助到初学者以及正在复习数据结构的人。同时也希望大家可以重视代码的规范性,提高代码的可阅读性。一定要做到见名知意。不要写出类似int a,b,c,d,e,f,g,以及不缩进不使用驼峰命名法的垃圾代码。

#include <iostream>
#include <cmath>

using namespace std;
#define MaxSize 20
#define Min 0.0001

int getPriority(char operation);

bool MedianCalculate(float operand_1, char operation, float operand_2, float &result);
/*
 * 与前两个的区别
 * 区别一:计算前缀式的时候,先出栈的操作数在左边,后出栈的操作数在右边
 * 区别二:从右到左扫描表达式
 * 区别三:循环条件不同
 */
float CalculatePreFix(const char *expression, int length);

int main() {
    char expression[MaxSize];

    return 0;
}

int getPriority(char operation) {
    if (operation == '+' || operation == '-')
        return 1;
    else if (operation == '*' || operation == '/')
        return 2;
    else if (operation == '^')
        return 3;
    else {
        cerr << "Invalid operator: " << operation << "! Please check! " << endl;
        return -1;
    }
}

float CalculatePreFix(const char *expression, int length) {
    float operand[MaxSize];
    int operand_top = -1;

    for (int expression_index = length - 1; expression[expression_index] > 0; --expression_index) {
        if (expression[expression_index] >= 0 && expression[expression_index] <= 9) {
            operand[++operand_top] = expression[expression_index] - '0';
        } else {
            float operand_1;
            float operand_2;
            float result;

            char operator_;
            bool flag;
            operand_1 == operand[operand_top--];
            operand_2 = operand[operand_top--];
            operator_ = expression[expression_index];
            flag = MedianCalculate(operand_1, operator_, operand_2, result);

            if (!flag) {
                cerr << "Sorry, there is something wrong with your operand or operator! Please check! " << endl;
            }

            operand[++operand_top] = result;
        }
    }

    return operand[operand_top];
}

bool MedianCalculate(float operand_1, char operation, float operand_2, float &result) {
    if (operation == '+') result = operand_1 + operand_2;
    if (operation == '-') result = operand_1 - operand_2;
    if (operation == '*') result = operand_1 * operand_2;
    if (operation == '/') {
        if (fabs(operand_2) < Min)
            return false;
    } else {
        result = operand_1 / operand_2;
    }

    return true;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

随风舞落叶殇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值