21xrx.com
2025-03-23 09:20:32 Sunday
文章检索 我的文章 写文章
C++实现带括号的四则运算
2023-06-24 06:11:40 深夜i     18     0
C++ Implementation Parentheses Arithmetic Operation

C++是一种广泛使用的编程语言,可以用来实现各种各样的应用程序。其中,带括号的四则运算是一种常见的计算操作,今天我们就来了解一下如何用C++实现这种计算。

首先,我们需要明确带括号的四则运算的计算优先级。一般来说,括号内的运算优先级最高,其次是乘法和除法,最后是加法和减法。因此,在计算时我们可以采用递归的方式,先计算括号内的运算,再按照优先级顺序计算其他部分。

具体实现时,我们可以采用字符串的方式来存储计算式。在读入字符串后,我们可以用栈来存储数字和操作符。遇到数字时,将它入栈;遇到操作符时,比较它的优先级和栈顶操作符的优先级,如果栈顶操作符优先级较高,则先将它计算出来再入栈,直到栈顶操作符优先级较低或相等为止。

当遇到左括号时,我们可以采用递归的方式计算括号内的运算,并将结果入栈;当遇到右括号时,说明一个括号内的运算结束,可以将栈中的数字和操作符计算出来。最后,栈中只剩下一个数字,即为最终结果。

下面是一段示例代码,可以实现带括号的四则运算:

#include <iostream>
#include <stack>
#include <string>
using namespace std;
int priority(char c) { // 计算操作符优先级
  if(c == '+' || c == '-') return 1;
  if(c == '*' || c == '/') return 2;
  return 0;
}
int operate(int a, int b, char op) { // 计算两个数字的结果
  if(op == '+') return a + b;
  if(op == '-') return a - b;
  if(op == '*') return a * b;
  if(op == '/') return a / b;
  return 0;
}
int calculate(string s) {
  stack<int> nums;
  stack<char> ops;
  int num = 0;
  for(int i = 0; i < s.size(); i++) {
    char c = s[i];
    if(c >= '0' && c <= '9') { // 遇到数字,将其读入
      num = num * 10 + (c - '0');
      if(i == s.size() - 1 || s[i+1] < '0' || s[i+1] > '9') {
        nums.push(num);
        num = 0;
      }
    } else if(c == '(') { // 遇到左括号,递归计算括号内的结果
      int j = i, cnt = 0;
      for(; j < s.size(); j++) {
        if(s[j] == '(') cnt++;
        if(s[j] == ')') cnt--;
        if(cnt == 0) break;
      }
      nums.push(calculate(s.substr(i+1, j-i-1)));
      i = j;
    } else if(c == '+' || c == '-' || c == '*' || c == '/') { // 遇到操作符,比较优先级
      while(!ops.empty() && priority(ops.top()) >= priority(c)) {
        int b = nums.top(); nums.pop();
        int a = nums.top(); nums.pop();
        nums.push(operate(a, b, ops.top()));
        ops.pop();
      }
      ops.push(c);
    }
  }
  while(!ops.empty()) { // 处理栈中剩余的操作符和数字
    int b = nums.top(); nums.pop();
    int a = nums.top(); nums.pop();
    nums.push(operate(a, b, ops.top()));
    ops.pop();
  }
  return nums.top(); // 返回最终结果
}
int main() {
  string s;
  getline(cin, s);
  cout << calculate(s) << endl;
  return 0;
}

这段代码可以读入一行计算式,并输出最终结果。例如,输入`(1+2)*(3+4)/5`,输出结果为`4`。

综上所述,我们可以用C++实现带括号的四则运算。这是一种基础的编程练习,也是很多应用程序的基础。欢迎读者们尝试使用C++实现这种计算操作,并在实践中不断提升编程技巧。

  
  

评论区

请求出错了