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 '\n': 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 '\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 << "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; } } } /* 完成前面高优先级的运算后,当前的运算符(除了‘\n’以外)变成最高优先级,所以应存储下来 */ if(command!='\n') operations.push(command); } break; } }

 

转载于:https://www.cnblogs.com/ticktack/p/6659420.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值