21xrx.com
2024-09-20 05:50:02 Friday
登录
文章检索 我的文章 写文章
C++实现表达式计算
2023-06-28 04:40:08 深夜i     --     --
C++ 表达式计算 实现

随着计算机科学技术的不断发展,表达式计算成为了计算机编程中不可或缺的一个方面。C++作为一种功能强大的编程语言,在表达式计算方面也有着极为优秀的表现。

C++中实现表达式计算通常采用的是栈的数据结构。首先,需要将用户输入的数学表达式进行分解,将数字和运算符分离开来。对于符号,我们可以将其分为加、减、乘、除等几个类型。然后,将分离出来的数字和符号依次压入栈中。

接下来,我们需要对栈中的元素进行处理。对于加、减符号,直接出栈相邻的两个数字,进行加或减运算,再将运算结果压入栈中;对于乘、除符号,则需要出栈相邻的两个数字,进行乘或除运算,再将运算结果压入栈中。最终,由于只剩下栈顶元素,因此该元素就是整个表达式的运算结果。

下面是一段C++代码实现一个简单的加减乘除表达式的计算:


#include <stack>

#include <iostream>

#include <cmath>

using namespace std;

double calculate(string input) {

  stack<double> nums;

  stack<char> ops;

  string temp;

  for (int i = 0; i < input.size(); i++) {

    if (input[i] >= '0' && input[i] <= '9') {

      temp += input[i];

    }

    else {

      if (temp.size() > 0) {

        nums.push(stod(temp));

        temp.clear();

      }

      if (input[i] == '+' || input[i] == '-') {

        while (!ops.empty() && (ops.top() == '*' || ops.top() == '/' || ops.top() == '+' || ops.top() == '-')) {

          char c = ops.top();

          ops.pop();

          double b = nums.top();

          nums.pop();

          double a = nums.top();

          nums.pop();

          if (c == '+') nums.push(a + b);

          else nums.push(a - b);

        }

        ops.push(input[i]);

      }

      else if (input[i] == '*' || input[i] == '/') {

        while (!ops.empty() && (ops.top() == '*' || ops.top() == '/')) {

          char c = ops.top();

          ops.pop();

          double b = nums.top();

          nums.pop();

          double a = nums.top();

          nums.pop();

          if (c == '*') nums.push(a * b);

          else nums.push(a / b);

        }

        ops.push(input[i]);

      }

    }

  }

  if (temp.size() > 0) {

    nums.push(stod(temp));

    temp.clear();

  }

  while (!ops.empty()) {

    char c = ops.top();

    ops.pop();

    double b = nums.top();

    nums.pop();

    double a = nums.top();

    nums.pop();

    if (c == '+') nums.push(a + b);

    else if (c == '-') nums.push(a - b);

    else if (c == '*') nums.push(a * b);

    else if (c == '/') nums.push(a / b);

  }

  return nums.top();

}

int main() {

  string input;

  cout << "Please enter a mathematical expression: ";

  cin >> input;

  cout << "Result: " << calculate(input) << endl;

  return 0;

}

以上就是一个简单的C++实现表达式计算的方法。当然,这仅仅是计算表达式的最基本方法,还有更加高效的算法和数据结构可以应用,需要根据具体情况进行选择。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复