#include<iostream>
#include<stdio.h>
#include<string.h>
#include<stack>
#include<iomanip>
using namespace std;
const int maxn = 201;
char s[maxn];
char lastexp[maxn];//后缀表达式串
bool Operator(char a)
{
if(a=='+'||a=='-'||a=='*'||a=='/')return true;
return false;
}
bool check(char l,char r)//左运算(栈内)符优先级高 返回真
{
int a1,a2;//规律:左右运算符都是减或都是乘除的情况下 左边优先
if(l=='+'||l=='-')
a1 = 2;
if(l=='*'||l=='/')
a1 = 4;
if(r=='+'||r=='-')
a2 = 1;
if(r=='*'||r=='/')
a2 = 3;
if(l=='=')
a1=0;
if(a1>a2)return 1;
else return 0;
}
int main()
{
stack<char> op;
stack<double> cul;
while(cin.getline(s,201)&&(s[0]!='0'||s[1]!='\0'))
{
char *exp = lastexp;
while(!op.empty())
op.pop();
while(!cul.empty())
cul.pop();
op.push('=');
int n = strlen(s);
s[n]=' ';
n++;
for(int i=0;i<n;i++)//将中缀表达式转化为后缀表达式
{
if(Operator(s[i]))
{
char ch = op.top();
while(check(ch,s[i]))//扫描到的运算符,与栈顶运算符优先级相比
{ //小于栈顶,栈顶运算符出栈并加入到后缀表达式中
*exp = ch; //重复这一过过程 ,直到高于栈顶运算符,
exp++; //并将此运算符加入到运算符栈中
op.pop();
ch = op.top();
}
op.push(s[i]);
}
else
{
*exp = s[i];
exp++;
}
}
while(op.top()!='=')
{
*exp = op.top();
op.pop();
exp++;
}
*exp = '\0';
//printf("%s\n",lastexp);
n = strlen(lastexp);
int num=0;
for(int i=0;i<n;i++)//后缀表达式借助栈进行运算
{
char ch = lastexp[i];
if(ch>='0'&&ch<='9')//如果是数字,加入计算栈
{
num = num*10+ (ch-'0');
if(lastexp[i+1]==' ')
{
cul.push(num);
num=0;
}
}
else if(Operator(ch))//如果是运算符,取栈顶两元素 进行运算
{
double a = cul.top();cul.pop();
double b = cul.top();cul.pop();
if(ch=='+')cul.push(b+a);
else if(ch=='-')cul.push(b-a);
else if(ch=='*')cul.push(b*a);
else cul.push(b/a);
}
}
double ans = cul.top();
cout<<setprecision(2)<<setiosflags(ios::fixed)<<ans<<endl;
}
}
hdu 1237 简单计算器
最新推荐文章于 2021-08-06 19:44:41 发布