NYOJ 267 郁闷的C小加(二)

郁闷的C小加(二)

时间限制: 1000 ms  |  内存限制: 65535 KB
难度: 4
描述

聪明的你帮助C小加解决了中缀表达式到后缀表达式的转换(详情请参考“郁闷的C小加(一)”),C小加很高兴。但C小加是个爱思考的人,他又想通过这种方法计算一个表达式的值。即先把表达式转换为后缀表达式,再求值。这时又要考虑操作数是小数和多位数的情况。

输入
第一行输入一个整数T,共有T组测试数据(T<10)。
每组测试数据只有一行,是一个长度不超过1000的字符串,表示这个运算式,每个运算式都是以“=”结束。这个表达式里只包含+-*/与小括号这几种符号。其中小括号可以嵌套使用。数据保证输入的操作数中不会出现负数并且小于1000000。
数据保证除数不会为0。
输出
对于每组测试数据输出结果包括两行,先输出转换后的后缀表达式,再输出计算结果,结果保留两位小数。两组测试数据之间用一个空行隔开。
样例输入
2
1+2=
(19+21)*3-4/5=
样例输出
12+=
3.00
1921+3*45/-=
119.20
AC码:
#include<stdio.h>
double fun(double a,double b,char x)
{
	if(x=='+')
		return b+a;
	if(x=='-')
		return b-a;
	if(x=='*')
		return b*a;
	if(x=='/')
		return b/a;
}
int main()
{
	int T,i,top1,top2;
	double x,t,num[1000],a,b;
	char str[1005],ch[1000];
	scanf("%d",&T);
	while(T--)
	{
		scanf("%s",str);
		top1=-1;
		top2=-1;
		for(i=0;str[i]!='\0';i++)
		{
			x=0;
			if(str[i]>='0'&&str[i]<='9')
			{
				while(str[i]>='0'&&str[i]<='9')
				{
					printf("%c",str[i]);
					x=x*10+str[i]-'0';
					i++;
				}
				if(str[i]=='.')
				{
					printf("%c",str[i]);
					i++;
					t=0.1;
					while(str[i]>='0'&&str[i]<='9')
					{
						printf("%c",str[i]);
						x=x+(str[i]-'0')*t;
						t=t*0.1;
						i++;
					}
				}
				top1++;
				num[top1]=x;
			}
			if(str[i]=='\0')
				break;
			if(str[i]=='(')
			{
				top2++;
				ch[top2]=str[i];
			}
			else if(str[i]==')')
			{
				while(top2>=0&&ch[top2]!='(')
				{
					printf("%c",ch[top2]);
					a=num[top1];
					top1--;
					b=num[top1];
					num[top1]=fun(a,b,ch[top2]);
					top2--;
				}
				top2--;
			}
			else if(str[i]=='*'||str[i]=='/')
			{
				while(ch[top2]=='*'||ch[top2]=='/')
				{
					printf("%c",ch[top2]);
					a=num[top1];
					top1--;
					b=num[top1];
					num[top1]=fun(a,b,ch[top2]);
					top2--;
				}
				top2++;
				ch[top2]=str[i];
			}
			else
			{
				while(top2>=0&&ch[top2]!='(')
				{
					printf("%c",ch[top2]);
					a=num[top1];
					top1--;
					b=num[top1];
					num[top1]=fun(a,b,ch[top2]);
					top2--;
				}
				top2++;
				ch[top2]=str[i];
			}
		}
		while(top2>=0)
		{
			printf("%c",ch[top2]);
			a=num[top1];
			top1--;
			b=num[top1];
			num[top1]=fun(a,b,ch[top2]);
			top2--;
		}
		printf("\n%.2f\n",num[0]);
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值