N 位四则算式计算器(小数和多层括号嵌套)

 

表达式计算

  1. 用vector<string> 来模拟大数(长度超过int 型整数长度)的存取和运算,初步实现了加法、减法、乘法、除法运算。
  2. 其中,乘法是基于循环加发实现的,除法是基于循环减法实现的。
  3. 表达式中可以嵌套多层括号,通过二叉树来实现运算符优先级的选取。

 

 

个人感觉用string来模拟大数运算效率有点低,但是string内的char 型只有一个字节,占用较小 的存取空间。

好的,我可以提供一个简单的实现,具体步骤如下: 1. 定义一个字符串变量,用于存储用户输入的算式。 2. 通过cin将用户输入的算式存入字符串变量中。 3. 定义一个函数,用于将字符串中的数字和运算符提取出来,并存储到两个栈中。 4. 定义一个函数,用于计算两个数的结果。 5. 定义一个函数,用于根据运算符的优先级进行计算。 6. 定义一个函数,用于计算整个算式的结果。 以下是示例代码: ```c++ #include <iostream> #include <stack> #include <cstring> using namespace std; // 判断字符是否为数字 bool isDigit(char c) { return c >= '0' && c <= '9'; } // 判断字符是否为运算符 bool isOperator(char c) { return c == '+' || c == '-' || c == '*' || c == '/'; } // 将字符串中的数字和运算符提取出来,并存储到两个栈中 void parseExpression(string expr, stack<int>& nums, stack<char>& ops) { int num = 0; bool hasNum = false; for (int i = 0; i < expr.length(); i++) { char c = expr[i]; if (isDigit(c)) { num = num * 10 + (c - '0'); hasNum = true; } else { if (hasNum) { nums.push(num); num = 0; hasNum = false; } if (isOperator(c)) { while (!ops.empty() && (ops.top() == '*' || ops.top() == '/') && (c == '+' || c == '-')) { int num2 = nums.top(); nums.pop(); int num1 = nums.top(); nums.pop(); char op = ops.top(); ops.pop(); nums.push(op == '+' ? num1 + num2 : num1 - num2); } ops.push(c); } else if (c == '(') { ops.push(c); } else if (c == ')') { while (ops.top() != '(') { int num2 = nums.top(); nums.pop(); int num1 = nums.top(); nums.pop(); char op = ops.top(); ops.pop(); nums.push(op == '+' ? num1 + num2 : num1 - num2); } ops.pop(); } } } if (hasNum) { nums.push(num); } while (!ops.empty()) { int num2 = nums.top(); nums.pop(); int num1 = nums.top(); nums.pop(); char op = ops.top(); ops.pop(); nums.push(op == '+' ? num1 + num2 : num1 - num2); } } // 计算两个数的结果 int calc(int num1, int num2, char op) { if (op == '+') { return num1 + num2; } else if (op == '-') { return num1 - num2; } else if (op == '*') { return num1 * num2; } else if (op == '/') { return num1 / num2; } return 0; } // 根据运算符的优先级进行计算 void calculate(stack<int>& nums, stack<char>& ops) { int num2 = nums.top(); nums.pop(); int num1 = nums.top(); nums.pop(); char op = ops.top(); ops.pop(); int result = calc(num1, num2, op); nums.push(result); } // 计算整个算式的结果 int evaluate(string expr) { stack<int> nums; stack<char> ops; parseExpression(expr, nums, ops); return nums.top(); } int main() { string expr; cout << "请输入算式:" << endl; cin >> expr; int result = evaluate(expr); cout << "结果为:" << result << endl; return 0; } ``` 这个实现还有一些不足之处,比如没有对输入的算式进行校验,如果用户输入的算式不符合规范,程序可能会崩溃。但是这个实现可以帮助你了解计算器程序的基本原理。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值