21xrx.com
2025-03-27 16:32:39 Thursday
文章检索 我的文章 写文章
"C++算术表达式求值代码分享"
2023-07-02 20:57:36 深夜i     --     --
C++ 算术表达式 求值 代码分享

C++算术表达式求值代码分享

在计算机科学中,算术表达式是由数字、运算符和括号组成的表达式。C++是一种流行的编程语言,通过使用C++语言编程可以轻松地计算算术表达式。本文将介绍如何使用C++编写算术表达式求值代码。

在C++中,算术表达式可以使用基本算术运算符,如加号(+)、减号(-)、乘号(*)和除号(/)等。算术表达式可以在C++程序中使用变量、常量和函数调用等其他表达式的组合。为了计算算术表达式,程序员必须掌握运算符优先级和结合律等重要概念。

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

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<string>
#include<stack>
#include<queue>
#include<map>
using namespace std;
int ans;
char ch[1001];
stack<int>number;
stack<char>op;
int compare(char x)//优先级比较。
{
  if(x=='*'||x=='/')return 2;
  if(x=='+'||x=='-')return 1;
  return -1;
}
void operate(char x)//操作函数。
{
  if(x=='+'||x=='-')
  {
    int b=number.top();number.pop();
    int a=number.top();number.pop();
    if(x=='+')number.push(a+b);
    else number.push(a-b);
  }
  else
  {
    int b=number.top();number.pop();
    int a=number.top();number.pop();
    if(x=='*')number.push(a*b);
    if(x=='/')number.push(a/b);
  }
}
int main()
{
  gets(ch);//读入算式。
  for(int i=0;ch[i];i++)
  {
    if(isdigit(ch[i]))
    {
      int u=0;
      while(isdigit(ch[i'])){u=u*10+(ch[i]-'0');i++;}
      i--;
      number.push(u);
    }
    else if(ch[i]=='(')op.push(ch[i]);
    else if(ch[i]==')')
    {
      while(!op.empty()&&op.top()!='(')
      {
        operate(op.top());
        op.pop();
      }
      op.pop();
    }
    else if(ch[i]=='*'||ch[i]=='/'||ch[i]=='+'||ch[i]=='-')
    {
      while(!op.empty()&&op.top()!='('&&compare(op.top())>=compare(ch[i]))
      {
        operate(op.top());
        op.pop();
      }
      op.push(ch[i]);
    }
  }
  while(!op.empty())
  {
    operate(op.top());
    op.pop();
  }
  printf("%d\n",number.top());//number.top()存放最后结果。
}

上述代码主要使用了堆栈的数据结构,堆栈是计算机科学中经常使用的数据结构之一。堆栈数据结构具有后进先出的特性,即最后一个进入堆栈的元素是第一个被弹出的元素。在这个算法中,我们使用了两个堆栈,一个用于存储数字,另一个用于存储操作符。

我们可以通过以下步骤解析这段代码:

1.使用gets()函数从控制台读入算术表达式。

2.遍历表达式中的每个字符,如果该字符是数字,就将其压入数字堆栈中。

3.如果该字符是左括号,就将其压入操作符堆栈中。

4.如果该字符是右括号,就从操作符堆栈中弹出元素,直到左括号出现,并对其进行操作。

5.如果该字符是运算符,则将该运算符与操作符栈顶元素进行比较;如果运算符比栈顶元素优先级低,则从操作符堆栈中弹出栈顶元素,并对其进行操作。然后将该运算符压入堆栈。

6.对操作符堆栈中余下的所有元素进行操作。

7.显示数字堆栈中的顶部元素,它包含了算术表达式的计算结果。

总之,本文介绍了使用C++编写算术表达式求值代码的方法。通过了解这个算法,你可以计算任何算术表达式的值。此外,在编写C++代码时,我们还使用了堆栈数据结构和其他重要概念。希望这篇文章能为你提供帮助,在你的编程工作中有所裨益。

  
  

评论区