在考研复习过程中,我发现严书上给出的代码非常不易于理解,并且搜索引擎搜到的一些博客所写的代码实在是一言难尽。所以在此更新一些根据我自己的理解写的代码,希望可以帮助到初学者以及正在复习数据结构的人。同时也希望大家可以重视代码的规范性,提高代码的可阅读性。一定要做到见名知意。不要写出类似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;
}