C++实现简易计算器(正则表达式计算)

说明:简单高效的C++代码,实现简易计算器(正则表达式计算),允许小数、括号。但没有表达式正误检验功能,所以测试前请确保式子正确哦

数据结构:栈

示范输入:

((1.5+2.5)*3-4)+5

42/7-(12+3)*0.5

标准输出:

the answer is 13

the answer is -1.5

源代码:

#include <iostream>
#include <stack> using namespace std; stack<double> numbers; //存储操作数 stack<char> operations; //存储运算符 /* 设定运算符的优先级,其中以'#'作为operations的栈底元素(便于之后操作) */ int priority(char operate) { switch (operate) { case '#':case ' ': return 0; case '(':case ')': return 1; case '+':case '-': return 2; case '*':case '/': return 3; } } void calculate(char); int main() { cout << "WELCOME CALCULATOR" << endl << endl << "input an algebrais expression to calculate or input 'q' to quit" << 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 ' ': /* 初始化栈底元素为'#'*/ if (operations.empty()) operations.push('#'); /* 若现在输入的运算符优先级较高或是输入‘(’,则应该存储现在的操作符,不执行之前的运算符 */ if (priority(command) > priority(operations.top()) || command == '(') operations.push(command); /* 若之前输入的运算符优先级较高,则之前的运算符应该被执行 */ else { while (priority(command) <= priority(operations.top())) { /* 当运算符完全实现后,露出栈底元素‘#’,输入“ ”则打印结果 */ if (operations.top() == '#' && command == ' ') { result = numbers.top(); cout << "the answer is " << 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; } } } /* 完成前面高优先级的运算后,当前的运算符(除了‘ ’以外)变成最高优先级,所以应存储下来 */ if(command!=' ') operations.push(command); } break; } }
原文地址:https://www.cnblogs.com/ticktack/p/6659420.html