gpt4 book ai didi

c++ - 以下代码段中 push(po[i] -'0' ) 对于评估后缀表达式的重要性是什么

转载 作者:行者123 更新时间:2023-11-28 05:28:23 25 4
gpt4 key购买 nike

实现 C++ 程序,将表达式转换为中缀到后缀,并根据给定条件使用堆栈对其进行评估操作数和运算符,都必须是单个字符。输入后缀表达式必须采用所需的格式。只需要“+”、“-”、“*”和“/”运算符
我不明白函数 evaluate() 中 push(po[i]-'0') 语句的重要性

#include<iostream>
using namespace std;

class stack
{
char st[20],in[20],po[20];
int TOP,k;
public:
stack()
{
TOP=-1;
k=0;
}
void infixToPostfix();
void evaluate();
private:
void push(char);
char pop();
int precedence(char);
};

void stack::push(char ch)
{
if(TOP==19)
{
cout<<"Stack overflow"<<endl;
}
else
{
TOP++;
st[TOP]=ch;
}
}

char stack::pop()
{
if(TOP==-1)
{
cout<<"Stack underflow"<<endl;
return 0;
}
else
{
int m=st[TOP];
TOP--;
return m;
}
}

void stack::evaluate()
{
cout<<"The postfix expression is"<<endl<<po<<endl;;
int a,b,res,temp;
TOP=-1;
for(int i=0;po[i]!='\0';i++)
{
if(isdigit(po[i])==1)
{
push(po[i]-'0');
}
else
{
a=pop();
b=pop();
switch(po[i])
{
case '+': res=b+a;
break;
case '-': res=b-a;
break;
case '*': res=b*a;
break;
case '/': res=b/a;
break;
}
push(res);
}
}
temp=pop();
cout<<"The answer is "<<temp<<endl;
}

void stack::infixToPostfix()
{
int m;
char left='(',right=')';
cout<<"Enter infix expression"<<endl;
cin>>in;
for(int i=0;in[i]!='\0';i++) //if operand add it to postfix
{
if(isalpha(in[i])==1 || isdigit(in[i]==1))
{
po[k]=in[i];
k++;
}
else if(in[i]==left) //if left parenthesis then push it to stack;
{
push(left);
}
else if(in[i]==right) //if right parenthesis encountered then pop from stack until left parenthesis
{
while((m=pop())!=left)
{
po[k]=m;
k++;
}
}
else //if operator is encounterd pop from the stack the operands having equal or higher precedence
{
while(precedence(st[TOP])>=precedence(in[i]))
{
int m=pop();
po[k]=m;
k++;
}
push(in[i]);
}
}
while(TOP>=0)
{
po[k]=pop();
k++;
}
po[k]='\0';
cout<<"The postfix expression is"<<endl;
cout<<po;
}

int stack::precedence(char ch)
{
if(ch=='+' || ch=='-')
{
return 1;
}
else if(ch=='*' || ch=='/')
{
return 2;
}
else if(ch=='(')
{
return 0;
}
}

int main()
{
stack s;
int op;
do
{
cout<<"\n____________________________"<<endl;
cout<<"1 Postfix to infix conversion"<<endl;
cout<<"2 Evaluation of postfix"<<endl;
cout<<"3 Exit"<<endl;
cout<<"______________________________"<<endl;
cin>>op;
switch(op)
{
case 1: s.infixToPostfix();
break;
case 2: s.evaluate();
break;
case 3:break;
default: cout<<"Enter correct option"<<endl;
}
}while(op!=3);
return 0;
}

最佳答案

它将数字字符转换为数字(整数)。例如

if po[i] = '5'.

It pushes, '5'-'0' => 53-48 (their ascii values) = 5.

干杯。

关于c++ - 以下代码段中 push(po[i] -'0' ) 对于评估后缀表达式的重要性是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40055335/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com