21xrx.com
2025-06-20 02:46:35 Friday
文章检索 我的文章 写文章
C++实现四则混合运算的代码
2023-06-29 16:23:43 深夜i     34     0
C++ 四则混合运算 代码实现

C++是一种广泛使用的编程语言,它支持四则混合运算,并提供了丰富的库函数和工具来实现这个功能。下面,我们将介绍如何使用C++实现四则混合运算的代码。

首先,我们需要定义一个函数来计算一个表达式的值。这个函数可以使用递归的方式来处理表达式,从而实现四则混合运算。具体的代码如下:

#include <iostream>
using namespace std;
int getValue(string s, int& index) {
  int res = 0;
  char sign = '+';
  int n = s.size();
  while (index < n) {
    char c = s[index];
    if (isdigit(c)) {
      res = res * 10 + (c - '0');
    }
    if ((!isdigit(c) && c != ' ') || index == n - 1) {
      if (sign == '+') {
        stk.push(res);
      }
      else if (sign == '-') {
        stk.push(-res);
      }
      else if (sign == '*' || sign == '/') {
        int a = stk.top(); stk.pop();
        if (sign == '*') stk.push(a * res);
        else stk.push(a / res);
      }
      sign = c;
      res = 0;
    }
    if (c == ')') {
      index++;
      break;
    }
    index++;
  }
  int ans = 0;
  while (!stk.empty()) {
    ans += stk.top();
    stk.pop();
  }
  return ans;
}
int calculate(string s) {
  int index = 0;
  return getValue(s, index);
}

上面的代码中,getValue函数用递归的方式来实现四则混合运算,通过栈来保存数字并计算运算结果。calculate函数调用getValue函数来计算整个表达式的值,并返回结果。

我们可以使用以下示例代码来测试上述函数的正确性:

int main() {
  string s = "3+2*2";
  int result = calculate(s);
  cout << result << endl;
  return 0;
}

输出结果为7,符合预期。

总之,C++是一种功能强大的编程语言,它提供了许多库函数和工具来实现各种功能,包括四则混合运算。使用上述代码,我们可以轻松实现四则混合运算,并且能够正确地计算表达式的值。

  
  

评论区