计算器栈实现原理

计算器栈实现原理

1.为什么要使用栈来实现计算器?

在计算过程中由于计算拥有优先级关系,比如先乘除后加减,但是计算机读一段表达式只能一遍一遍并且一个一个的读,比如:3+2*4,我们直到要先将2*4算出之后才能和3相加,但是计算机在读这段表达式的时候只能一个读符一个字符的读,比如读到2就只能记住以前读到的结果,而无法预知以后的结果,所以在读完3+2时就只能计算3+2,而无法预知2*4要先进行计算。

栈就是一种用来储存数据的结构,他是一种类似于弹夹的数据结构,将子弹一颗一颗往里面装,最开始装进去的子弹,最后打出来。

有了栈之后便可以将表达式压栈之后根据运算符优先级关系来将栈中的内容有规律的取出,比如+-运算符优先级最低,那么最后将被压在栈底,而栈的顶部则

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,以下是C++实现简易计算器的代码: ```c++ #include <iostream> #include <stack> #include <string> using namespace std; int main() { stack<int> numStack; // 存储数字的 stack<char> opStack; // 存储运算符的 string expression; // 表达式字符串 cin >> expression; int len = expression.length(); for (int i = 0; i < len; i++) { char ch = expression[i]; if (ch >= '0' && ch <= '9') { // 如果是数字,入数字 numStack.push(ch - '0'); } else { // 如果是运算符 if (opStack.empty() || ch == '(') { // 如果运算符为空或者当前运算符是左括号,直接入 opStack.push(ch); } else if (ch == ')') { // 如果当前运算符是右括号,弹出运算符中的元素直到遇到左括号 while (opStack.top() != '(') { int num2 = numStack.top(); numStack.pop(); int num1 = numStack.top(); numStack.pop(); char op = opStack.top(); opStack.pop(); int result; if (op == '+') { result = num1 + num2; } else if (op == '-') { result = num1 - num2; } else if (op == '*') { result = num1 * num2; } else { result = num1 / num2; } numStack.push(result); } opStack.pop(); // 弹出左括号 } else { // 如果当前运算符是加减乘除 while (!opStack.empty() && opStack.top() != '(' && ((ch == '*' || ch == '/') || (opStack.top() == '+' || opStack.top() == '-'))) { int num2 = numStack.top(); numStack.pop(); int num1 = numStack.top(); numStack.pop(); char op = opStack.top(); opStack.pop(); int result; if (op == '+') { result = num1 + num2; } else if (op == '-') { result = num1 - num2; } else if (op == '*') { result = num1 * num2; } else { result = num1 / num2; } numStack.push(result); } opStack.push(ch); } } } while (!opStack.empty()) { // 处理剩余的运算符 int num2 = numStack.top(); numStack.pop(); int num1 = numStack.top(); numStack.pop(); char op = opStack.top(); opStack.pop(); int result; if (op == '+') { result = num1 + num2; } else if (op == '-') { result = num1 - num2; } else if (op == '*') { result = num1 * num2; } else { result = num1 / num2; } numStack.push(result); } cout << numStack.top() << endl; // 输出最终结果 return 0; } ``` 这个程序可以处理包含加减乘除和括号的表达式,但是没有考虑负数的情况。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值