//逆波兰输出
#include <iostream>
using namespace std;
#include <string.h>
double opt(double a,double b,char op)
{
if(op=='+')
return a+b;
if(op=='-')
return b-a;
if(op=='*')
return a*b;
if(op=='/')
return b/a;
}//计算
double fun(char exp[])
{
double s[100];
int top=-1;double temp=0.0;
double scale=10.0;
int i=0;
bool flag=false;//用flag标记当前在处理整数还是小数
while(exp[i]!='#')
{
if(exp[i]>='0'&&exp[i]<='9'||exp[i]=='.')
{
while(exp[i]>='0'&&exp[i]<='9'||exp[i]=='.')
{
if(exp[i]>='0'&&exp[i]<='9'&&flag==false)
temp=temp*10+exp[i]-'0';//是整数
if(exp[i]>='0'&&exp[i]<='9'&&flag==true)
{
temp+=(exp[i]-'0')/scale;
scale*=10;//是小数
}
else if(exp[i]=='.')
flag=true;//遇到.标记当前马上要处理小数
i++;
}
cout<<"拼数结果是"<<temp<<endl;
s[++top]=temp;
temp=0.0;scale=10.0;
}
else if(exp[i]==',')
{
flag=false;
i++;//用,分割数字。不知道为什么如果用空格程序识别不出
}
else
{
double a,b,c;
a=s[top--];
//cout<<"取出的是"<<a<<endl;
b=s[top--];
//cout<<"取出的是"<<a<<endl;
//cout<<"运算符是"<<exp[i]<<endl;
c=opt(a,b,exp[i]);
s[++top]=c;
i++;
}
}
return s[top];
}
int main()
{
char exp[100];char x;
for(int i=0;i<20;i++)
{
cin>>x;
exp[i]=x;
if(x=='#')
break;
}
cout<<fun(exp)<<endl;
return 0;
}
9.29日更新:
今天重做了一遍有了新思路。
#include <iostream>
using namespace std;
#include <string.h>
#include <stack>
double opt(double a,double b,char op)
{
if(op=='+')
return a+b;
if(op=='-')
return a-b;
if(op=='*')
return a*b;
if(op=='/')
return a/b;
}
void expr(char s[],int len)
{
stack <double> num;
int i=0;
while(i<len)
{
if(s[i]>='1'&&s[i]<='9')
{
double temp=0.0;
while(s[i]>='1'&&s[i]<='9')
{
temp=temp*10+s[i]-'0';
i++;
}//最后一次i++如果后面有小数点,则继续处理小数部分
if(s[i]=='.')
{
double scale=10.0;
i++;
while(s[i]>='1'&&s[i]<='9')
{
temp+=(s[i]-'0')/scale;//记得s[i]是字符型,一定要-'0'转为int
scale*=10;
i++;
}//最后一次i++指向空格
}
num.push(temp);
}
else if(s[i]==' ')
i++;
else{
double b=num.top();
num.pop();
double a=num.top();
num.pop();
double res=opt(a,b,s[i]);
num.push(res);
i++;
}
}
cout<<"计算结果是:"<<num.top()<<endl;
}
int main()
{
char s[100];int len=0;
while((s[len]=getchar())!='!')
len++;
expr(s,len);
return 0;
}
运行结果: