逆波兰(后缀)表达式求值,有小数拼数

//逆波兰输出
#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;
}

运行结果:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值