21xrx.com
2025-07-05 19:57:50 Saturday
文章检索 我的文章 写文章
C++算数表达式求值代码
2023-06-22 13:08:10 深夜i     11     0
C++ 算数表达式 求值 代码

C++是一种强类型语言,它可以用来进行各种算数操作。其中,算数表达式求值是C++编程中的一个重要环节。为了实现算数表达式求值,我们需要使用一些C++代码。

以下是一个简单的C++算数表达式求值代码:

#include <iostream>
#include <stack>
#include <string>
using namespace std;
int operation(char op, int a, int b)
{
  switch(op)
  {
    case '+': return a + b;
    case '-': return a - b;
    case '*': return a * b;
    case '/': return a / b;
    case '%': return a % b;
  }
  return 0;
}
int evaluate(string str)
{
  stack<int> nums;
  stack<char> ops;
  for(int i = 0; i < str.length(); i++)
  {
    if(str[i] == ' ')
      continue;
    else if(str[i] >= '0' && str[i] <= '9')
    {
      int num = 0;
      while(i < str.length() && str[i] >= '0' && str[i] <= '9')
      {
        num = num * 10 + (str[i] - '0');
        i++;
      }
      i--;
      nums.push(num);
    }
    else if(str[i] == '(')
      ops.push(str[i]);
    else if(str[i] == ')')
    {
      while(!ops.empty() && ops.top() != '(')
      {
        int b = nums.top();
        nums.pop();
        
        int a = nums.top();
        nums.pop();
        
        char op = ops.top();
        ops.pop();
        
        nums.push(operation(op, a, b));
      }
      if(!ops.empty())
        ops.pop();
    }
    else if(str[i] == '+' || str[i] == '-' || str[i] == '*' || str[i] == '/' || str[i] == '%')
    {
      while(!ops.empty() && (ops.top() == '*' || ops.top() == '/' || ops.top() == '%'))
      {
        int b = nums.top();
        nums.pop();
        
        int a = nums.top();
        nums.pop();
        
        char op = ops.top();
        ops.pop();
        
        nums.push(operation(op, a, b));
      }
      ops.push(str[i]);
    }
  }
  
  while(!ops.empty())
  {
    int b = nums.top();
    nums.pop();
    
    int a = nums.top();
    nums.pop();
    
    char op = ops.top();
    ops.pop();
    
    nums.push(operation(op, a, b));
  }
  
  return nums.top();
}
int main()
{
  string expr = "10 + 2 * 6";
  int result = evaluate(expr);
  cout << "The result of " << expr << " is: " << result << endl;
  return 0;
}

这段代码包含了evaluate()函数和operation()函数。其中,evaluate()函数通过使用栈和循环语句来解析算数表达式,并对其进行求值。在该函数中,我们可以使用operation()函数来执行算术运算。

具体地说,evaluate()函数首先创建了两个栈:nums和ops。nums用于存储整数,而ops用于存储操作符。随后,循环读取算数表达式中的每个字符。如果该字符是空格,则跳过;如果该字符是数字,则将其解析为一个整数,并将其推入nums栈中;如果该字符是左括号,则将其推入ops栈中;如果该字符是右括号,则不断将ops栈中的操作符弹出,直到遇到左括号为止,并且将nums栈中相应的整数进行计算和替换;如果该字符是加减乘除或者余数操作符,则不断将ops栈中优先级高于该操作符的操作符弹出,直到该栈顶操作符的优先级不高于该操作符为止,并且将nums栈同样进行相应的计算和替换。最终,evaluate()函数返回nums栈中剩余的唯一一个整数,即算数表达式的求值结果。

通过上面这段C++代码,我们可以实现算数表达式求值功能。不过需要注意,我们只对包含加减乘除和余数操作符的简单算数表达式进行了支持,而不支持其它较为复杂的表达式。如果需要对复杂算数表达式进行求值,还需要做更多的改进和扩展。

  
  

评论区