表达式求值 NYOJ

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

char str[1005];
char changestr[2010];
double stack_n[1005];
char stack_c[1005];
int count_c = -1;
int count_n = -1;


char pop_c(){
	return stack_c[count_c--];
}

char top_c(){
	if(-1 == count_c)
	return 0;
	return stack_c[count_c];
}

void push_c(char t){
	stack_c[++count_c]=t;
}

double top_n(){
	if(-1 == count_n)
	return 0;
	return stack_n[count_n];
}

double pop_n(){
	return stack_n[count_n--];
}

void push_n(double t){
	stack_n[++count_n]=t;
}

int level(char ch){
	switch(ch)
	{
	case '+':
	case '-':return 1;
	case '*':
	case '/':return 2;
	default:
		return 0;
	}
}

void change()
{
	int i;
	int j=0;
	for(i=0; i<strlen(str);)
	{
		switch(str[i])
		{
		case '(':push_c('(');i++;break;
		case ')':
			while(top_c()!='('&&count_c!=-1)
			{
				changestr[j++] = pop_c();
				changestr[j++] = ' ';
			}
			pop_c();
			i++;break;
		case '+':
		case '-':
		case '*':
		case '/':
			while(level(str[i])<=level(top_c()))
			{
				changestr[j++] = pop_c();
				changestr[j++] = ' ';
			}
			push_c(str[i]);
			i++;break;
		case '=':i++;break;
		default:
			{
				while(str[i]<='9'&&str[i]>='0'||str[i]=='.')
					changestr[j++] = str[i++];
				changestr[j++] = ' ';
			}
		}
	}
	while(count_c!=-1)
	{
		changestr[j++] = pop_c();
		changestr[j++] = ' ';
	}
}

double result(){
	int i;
	int len = strlen(changestr);
	double x;
	double y;
	for(i=0; i<len; i++)
	{
		switch(changestr[i])
		{
			case '+':x = pop_n();x += pop_n();i++;break;
			case '-':x = pop_n();x = pop_n()-x;i++;break;
			case '*':x = pop_n();x *= pop_n();i++;break;
			case '/':x = pop_n();x = pop_n()/x;i++;break;
			default:
				x = 0;
				while(changestr[i]<='9'&&changestr[i]>='0')
				{
					x= x*10 + changestr[i] - '0';
					i++;
				}
				if(changestr[i] == '.')
				{
					double k = 10.0;
					y = 0;
					i++;
					while(changestr[i]<='9'&&changestr[i]>='0')
					{
						y+=((changestr[i]-'0')/k);
						i++;
						k*=10;
					}
					x+=y;
				}
		}
		push_n(x);
	}
	return top_n();
}

int main()
{
	int n;
	scanf("%d",&n);
	getchar();
	while(n--)
	{
		count_c = -1;
		count_n = -1;
		scanf("%s",str);
		change();
		printf("%.2f\n",result());
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值