21xrx.com
2024-06-03 04:40:28 Monday
登录
文章检索 我的文章 写文章
C++算术表达式求值代码
2023-07-11 06:49:17 深夜i     --     --
C++ 算术表达式 求值 代码

在C++编程中,算术表达式的求值是非常常见的任务之一。在进行算术表达式求值时,我们需要了解运算符的优先级和结合性,以便正确地计算表达式的值。

这里提供一段C++代码,可以计算算术表达式的值,包括加减乘除四则运算,以及括号的优先级。


#include<iostream>

#include<stack>

#include<cstring>

using namespace std;

int pre(char ch){//判断符号优先级

  if(ch == '+' || ch == '-') return 1;

  if(ch == '*' || ch == '/') return 2;

  return 0;

}

void calc(stack<int>& num, stack<char>& op){//计算部分

  int b = num.top(); num.pop();

  int a = num.top(); num.pop();

  char c = op.top(); op.pop();

  int ans;

  switch(c){

    case '+': ans = a + b; break;

    case '-': ans = a - b; break;

    case '*': ans = a * b; break;

    case '/': ans = a / b; break;

  }

  num.push(ans);

}

int main(){

  string s;

  cin>>s;

  stack<int> num;

  stack<char> op;

  for(int i = 0; i < s.size(); i++){//遍历表达式

    if(s[i] == ' ') continue;

    if(s[i] >= '0' && s[i] <= '9'){//处理数字

      int x = s[i] - '0';

      i++;

      while(i < s.size() && s[i] >= '0' && s[i] <= '9'){

        x = x * 10 + s[i] - '0';

        i++;

      }

      num.push(x);

      i--;

    }else if(s[i] == '('){//左括号

      op.push(s[i]);

    }else if(s[i] == ')'){//右括号

      while(op.top() != '('){

        calc(num, op);

      }

      op.pop();

    }else{//运算符

      while(!op.empty() && pre(op.top()) >= pre(s[i])){

        calc(num, op);

      }

      op.push(s[i]);

    }

  }

  while(!op.empty()){//处理栈中剩余运算

    calc(num, op);

  }

  cout<<num.top()<<endl;//输出最终结果

  return 0;

}

使用该算法,可以对算术表达式进行求值,并输出结果。需要注意的是,该算法不支持负数的运算,如需求解负数运算,需要进行相应的修改。

  
  

评论区

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