#include iostream#include stackusing namespace std;stackdouble numbers; 存储操作数stackchar operations; 存储运算符 设定运算符的优先级其中以#作为operations的栈底元素便于之后操作 int prioritychar operate switch operate case #ca
#include
stack
/* 设定运算符的优先级,其中以'#'作为operations的栈底元素(便于之后操作) / int priority(char operate) { switch (operate) { case '#':case '\n': return 0; // 栈底元素和换行符的优先级为0 case '(':case ')': return 1; // 括号的优先级为1 case '+':case '-': return 2; // 加减号的优先级为2 case '':case '/': return 3; // 乘除号的优先级为3 } }
void calculate(char);
int main() { cout<< "输入需要计算的式子,按q退出" << endl << endl; char command = cin.get(); // 读入第一个字符 while (command != 'q') { calculate(command); // 进行计算 command = cin.get(); // 读入下一个字符 } return 0; }
void calculate(char command) { double num, leftNum, rightNum, result;
switch (command)
{
/* 如果输入是数字,则将该double类型的数据存入栈中 */
case '0':case'1':case '2':case'3':case '4':case'5':case '6':case'7':case '8':case'9':
cin.putback(command); // 将数字字符放回输入流中
cin >> num; // 读入数字
numbers.push(num); // 存入栈中
break;
case '(':case ')':case '+':case '-':case '*':case '/':case '\n':
/* 初始化栈底元素为'#'*/
if (operations.empty())
operations.push('#');
/* 若现在输入的运算符优先级较高或是输入‘(’,则应该存储现在的操作符,不执行之前的运算符 */
if (priority(command) > priority(operations.top()) || command == '(')
operations.push(command);
/* 若之前输入的运算符优先级较高,则之前的运算符应该被执行 */
else {
while (priority(command) <= priority(operations.top()))
{
/* 当运算符完全实现后,露出栈底元素‘#’,输入“\n”则打印结果 */
if (operations.top() == '#' && command == '\n') {
result = numbers.top(); // 取出栈顶元素作为结果
cout << result << endl << endl; // 打印结果
numbers.pop(); // 弹出栈顶元素
operations.pop(); // 弹出栈顶元素
break; // 结束循环
}
/* 当括号内运算符完全实现后,去除括号,读入下一个字符 */
else if (operations.top() == '(' && command == ')') {
operations.pop(); // 弹出左括号
cin >> command; // 读入下一个字符
}
/* 若非上述两种情况,则完成前一个运算符,即operations.top() */
else {
rightNum = numbers.top(); // 取出栈顶元素作为右操作数
numbers.pop(); // 弹出栈顶元素
leftNum = numbers.top(); // 取出栈顶元素作为左操作数
numbers.pop(); // 弹出栈顶元素
switch (operations.top()) // 执行栈顶操作符
{
case '+':
numbers.push(leftNum + rightNum);
operations.pop(); // 弹出栈顶元素
break;
case '-':
numbers.push(leftNum - rightNum);
operations.pop(); // 弹出栈顶元素
break;
case '*':
numbers.push(leftNum * rightNum);
operations.pop(); // 弹出栈顶元素
break;
case '/':
numbers.push(leftNum / rightNum);
operations.pop(); // 弹出栈顶元素
break;
}
}
}
/* 完成前面高优先级的运算后,当前的运算符(除了‘\n’以外)变成最高优先级,所以应存储下来 */
if (command != '\n')
operations.push(command);
}
break;
}
原文地址: https://www.cveoy.top/t/topic/fKRq 著作权归作者所有。请勿转载和采集!