#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <limits.h>
#include <stack>
using namespace std;
struct datas
{
union
{
int data;
char ope;
};
bool status;
}d[1000],hz[1000];
int hl = 0;
int sum = 0,l=0;
void getDatas(char s[])
{
for(int i = 0;s[i]!='\0';i++)
{
if(s[i]>='0'&&s[i]<='9')
{
sum *= 10;
sum += s[i] - '0';
if(s[i+1]>'9'||s[i+1]<'0'||s[i+1]=='\0')
{
d[l].data = sum;
d[l].status = 1;
l++;
sum = 0;
}
}
else if((s[i]=='+'||s[i]=='-'||s[i]=='*'||s[i]=='/'||s[i]=='('||s[i]==')'))
{
d[l].ope = s[i];
d[l].status = 0;
l++;
sum = 0;
}
}
}
void printdatas(datas d[],int len)
{
for(int i = 0;i<len;i++)
{
if(d[i].status==1)
{
printf("%d",d[i].data);
}
else if(d[i].status==0)
{
printf(" %c ",d[i].ope);
}
}
cout<<endl;
}
bool isSmall(char a,char b)
{
if((a=='+'||a=='-')&&(b=='*'||b=='/'))
return true;
else if((a=='+'||a=='-')&&(b=='+'||b=='-'))
return true;
else if((a=='*'||a=='/')&&(b=='*'||b=='/'))
return true;
else
return false;
}
void trans(datas d[])
{
stack<datas> sta;
for(int i = 0;i<l;i++)
{
if(d[i].status==1)
{
hz[hl] = d[i];
hl++;
//printf("%d",d[i].data);
}
else
{
if(sta.empty())
{
sta.push(d[i]);
}
else if(d[i].ope=='(')
{
sta.push(d[i]);
}
else if(d[i].ope==')')
{
while(!sta.empty()&&(sta.top()).ope!='(')
{
datas temp = sta.top();
sta.pop();
//printf("%c",temp.ope);
hz[hl] = temp;
hl++;
}
sta.pop();
}
else
{
while(!sta.empty()&&isSmall(d[i].ope,(sta.top()).ope))
{
datas temp = sta.top();
sta.pop();
//printf("%c",temp.ope);
hz[hl] = temp;
hl++;
}
sta.push(d[i]);
}
}
}
while(!sta.empty())
{
datas temp = sta.top();
sta.pop();
//printf("%c",temp.ope);
hz[hl] = temp;
hl++;
}
}
//1*2+(3-4/5)*6
double getResult(datas hz[],int len,int &error)
{
error = 0;
stack<double> sta;
for(int i = 0;i<len;i++)
{
if(hz[i].status==1)
{
sta.push(hz[i].data);
}
else
{
double x = sta.top();
sta.pop();
double y = sta.top();
sta.pop();
double temp;
if(hz[i].ope=='+')
{
sta.push(y+x);
}
else if(hz[i].ope=='-')
{
sta.push(y-x);
}
else if(hz[i].ope=='*')
{
sta.push(y*x);
}
else if(hz[i].ope=='/')
{
if(x==0)
{
printf("除数不能为零\n");
error = 1;
return INT_MIN;
}
sta.push(y/x);
}
}
}
return sta.top();
}
int main()
{
char s[10000];
while(scanf("%s",s))
{
l = 0;
hl = 0;
getDatas(s);
//printdatas(d,l);
trans(d);
//cout<<endl;
//printdatas(hz,hl);
int error;
double res = getResult(hz,hl,error);
if(!error)
cout<<res<<endl;
}
return 0;
}
C语言版----代数式计算器
最新推荐文章于 2022-06-08 15:21:24 发布