利用栈实现算术表达式的求值,表达式中可以包含加、减、乘、除、乘方、括号运算符,参加运算的操作数可以是实数。
输入
输入一个算术表达式,以‘#’结尾。
-2.1+2*(-4.5+1.5*2)/4-2^2#
输出
输出算术表达式的结果(保留两位小数)。
-6.85
代码:
#include<iostream>
#include<stack>
#include<math.h>
#include<cstring>
#include<cstdio>
#include<cctype>
using namespace std;
stack<char> op;
stack<double> num;
int GetIndex(char a)
{
int index=0;
switch(a)
{
case '+':
index=0;
break;
case '-':
index=1;
break;
case '*':
index=2;
break;
case '/':
index=3;
break;
case '(':
index=4;
break;
case ')':
index=5;
break;
case '#':
index=6;
break;
case '^':
index=7;
break;
default :break;
}
return index;
}
char GetPriority(char op1,char op2)
{
char priority[][8]=
{
{ '>','>','<','<','<','>','>','<' },
{ '>','>','<','<','<','>','>','<' },
{ '>','>','>','>','<','>','>','<' },
{ '>','>','>','>','<','>','>','<' },
{ '<','<','<','<','<','=','0','>' },
{ '>','>','>','>','0','>','>','<' },
{ '<','<','<','<','<','0','=','<' },
{'>','>','>','>','<','>','>','>' },
};
int index1=GetIndex(op1);
int index2=GetIndex(op2);
return priority[index1][index2];
}
double calculate(double m,char b,double n)
{
switch(b)
{
case '+':
//cout<<"a"<<m+n<<endl;;
return m+n;
case '-':
//cout<<"b"<<n-m<<endl;;
return n-m;
case '*':
//cout<<"c"<<m*n<<endl;;
return m*n;
case '/':
//cout<<n/m<<endl;;
return 1.00*(n/m);
case '^':
//cout<<pow(n,m)<<endl;
return pow(n,m);
default:
break;
}
}
bool isdigit1(char c)
{
if(c>=48&&c<=57)
return true;
else
return false;
}
double GetAnswer()
{
op.push('#');
int count=0;//记录多少数字入栈
char c=getchar();
if(c=='-')
num.push(0);
int flag=0;
//cout<<"hello";
while(c!='#'||op.top()!='#')
{
if(isdigit(c)||c=='.')
{
//cout<<c<<endl;
if(count==1&&c!='.')
{
double t=num.top();
num.pop();
num.push(t*10+(c-'0'));
count=1;
}
else if(c=='.'||count==2)
{
c=getchar();
double t=num.top();
num.pop();
double x=c-'0';
num.push(t+x*0.1);
count=2;
}
else
{
num.push(c-'0');
count++;
}
c=getchar();
flag=1;
}
else
{
if(c=='-'&&(op.top()=='(')&&flag==0)
{
num.push(0);
}
count=0;
switch(GetPriority(op.top(),c))
{
case '<':
op.push(c);
c=getchar();
break;
case '=':
op.pop();
c=getchar();
break;
case '>':
char theta=op.top();
op.pop();
double a=num.top();
num.pop();
double b=num.top();
num.pop();
num.push(calculate(a,theta,b));
}
flag=0;
}
}
return num.top();
}
int main()
{
while(!num.empty())
num.pop();
while(!op.empty())
op.pop();
double x=GetAnswer();
printf("%.2lf",x);
return 0;
}
参考链接:
https://blog.csdn.net/bestfsq/article/details/55823298