利用栈的原理实现“加减乘除”的相关操作。
例如以下为输入:
2*3-4/3
可以正常的输出最终的结果:4.67
#include<iostream>
#include<string>
#include<cassert>
using std::cin;
using std::cout;
using std::endl;
using std::string;
//定义模板类,模拟栈的先入后出
template<typename Type> class Stack {
private:
int top_index, max_length;
Type *elements;
public:
Stack(const int & input_maxlength) {
elements = new Type[input_maxlength];
max_length = input_maxlength;
top_index = -1;
}
~Stack() {
delete [] elements;
}
//进栈
bool push(double element) {
if (top_index > max_length - 1) {
return false;
}
++top_index;
elements[top_index] = element;
return true;
}
//出栈
bool pop() {
if (top_index < 0) {
return false;
}
--top_index;
return true;
}
Type top() {
assert(top_index >= 0);
return elements[top_index];
}
bool empty() {
return top_index < 0;
}
};
//判断操作符的优先级
bool precede(char a, char b) {
if ( (a == '*' || a == '/') && (b == '+' || b == '-'))
return true;
else
return false;
}
//进行“加减乘除”的运算,需要注意两个操作数的前后位置
float operate(char theta, double a, double b) {
switch (theta) {
case '*':
return a * b;
case '/':
return a / b;
case '+':
return a + b;
case '-':
return a - b;
}
}
//弹出数字栈的两个数,与符号栈的一个符号,进行计算。
//并将计算结果再次入进数字栈
void calc(Stack<double> & numbers, Stack<char> & operators) {
double a = numbers.top();
numbers.pop();
double b = numbers.top();
numbers.pop();
char opr = operators.top();
operators.pop();
double result = operate(opr, b, a);
numbers.push(result);
}
int main() {
//输入需要输入的字符个数
int m;
cin >> m;
Stack<double> numbers(m);
Stack<char> operators(m);
//输入字符
string buffer;
cin >> buffer;
int i = 0;
while (i < m) {
if (isdigit(buffer[i])) {
//如果是数字,进入数字栈
numbers.push(buffer[i] - '0');
++i;
} else {
//如果符号栈为空,或者buffer中的符号的优先级高于符号栈顶层符号,将buffer[i]入进符号栈
if (operators.empty() || precede(buffer[i], operators.top())) {
operators.push(buffer[i]);
++i;
} else {
//否则进行计算
calc(numbers, operators);
}
}
}
//将符号栈清空
while (!operators.empty()) {
calc(numbers, operators);
}
printf("%.2f\n", numbers.top());
return 0;
}