C/C++ 算法 中缀转后缀表达式实现3---实现浮点数加减乘除四则算数(包括括号)
如:输入:12.2/2+(10+4)/7+2.5*2.5-1,输出:13.35
代码如下:
#include<iostream>
#include<stack>
using namespace std;
bool isoperator(char ch);
int priority(char ch);
void infix_to_postfix(char infix[],char postfix[]);
double getpostfix_value(char postfix[]);
int main(){
char infix[]="12.2/2+(10+4)/7+2.5*2.5-1";
cout<<infix<<endl;
char postfix[1024];
infix_to_postfix(infix,postfix);
cout<<postfix<<endl;
double result=getpostfix_value(postfix);
cout<<result<<endl;
return 0;
}
bool isoperator(char ch)
{
switch(ch)
{
case '+':
case '-':
case '*':
case '/':
return true;
default:
return false;
}
}
int priority(char ch)
{
switch(ch)
{
case '(':
return 0;
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
default:
return -1;
}
}
void infix_to_postfix(char infix[],char postfix[])
{
stack<char> s1;
s1.push('#');
int i=0,j=0;
while(infix[i]!='\0')
{
if((infix[i]>='0'&&infix[i]<='9')||infix[i]=='.')
{
postfix[j++]=infix[i];
}
else if(infix[i]=='(')
{
s1.push(infix[i]);
}
else if(infix[i]==')')
{
while(s1.top()!='(')
{
postfix[j++]=' ';
postfix[j++]=s1.top();
s1.pop();
}
s1.pop();
}
else if(isoperator(infix[i]))
{
postfix[j++]=' ';
if(s1.empty())
{
s1.push(infix[i]);
}
else
{
while(priority(infix[i])<=priority(s1.top()))
{
postfix[j++]=s1.top();
postfix[j++]=' ';
s1.pop();
}
s1.push(infix[i]);
}
}
i++;
}
while(s1.size())
{
postfix[j++]=' ';
postfix[j++]=s1.top();
s1.pop();
}
postfix[j-1]='\0';
}
double getpostfix_value(char postfix[])
{
stack<double> s1;
int i=0;
double result=0;
double x1=0,x2=0;
while(postfix[i]!='\0')
{
if(postfix[i]>='0'&&postfix[i]<='9')
{
double x=0;
int n=0;//counting the number of point
while(postfix[i]>='0'&&postfix[i]<='9')
{
x=x*10+(postfix[i]-'0');
i++;
}
//deal point
if(postfix[i]=='.')
{
i++;
while(postfix[i]>='0'&&postfix[i]<='9')
{
x=x*10+(postfix[i]-'0');
i++;
n++;
}
}
while(n)
{
x/=10;
n--;
}
s1.push(x);
}
else if(postfix[i]==' ')
{
i++;
}
else if(postfix[i]=='+')
{
x1=s1.top();
s1.pop();
x2=s1.top();
s1.pop();
double temp=x2+x1;
s1.push(temp);
i++;
}
else if(postfix[i]=='-')
{
x1=s1.top();
s1.pop();
x2=s1.top();
s1.pop();
double temp=x2-x1;
s1.push(temp);
i++;
}
else if(postfix[i]=='*')
{
x1=s1.top();
s1.pop();
x2=s1.top();
s1.pop();
double temp=x2*x1;
s1.push(temp);
i++;
}
else if(postfix[i]=='/')
{
x1=s1.top();
s1.pop();
x2=s1.top();
s1.pop();
double temp=x2/x1;
s1.push(temp);
i++;
}
}
result=s1.top();
return result;
}
运行结果: