XYNUOJ 第四次考試 表達式求值

問題 B: 表達式求值

時間限制: 3 Sec  內存限制: 6 MB
[提交][狀態][討論版]

題目描述

實現輸入一個表達式求出它的值的計算器,比如輸入:“1+2/4=”,程序就輸出1.50(結果保留兩位小數)

輸入

第一行輸入一個整數n,共有n組測試數據(n<10)。 每組測試數據只有一行,是一個長度不超過1000的字符串,表示這個運算式,每個運算式都是以“=”結束。這個表達式裏只包含+-*/與小括號這幾種符號。其中小括號可以嵌套使用。數據保證輸入的操作數中不會出現負數。 數據保證除數不會爲0

輸出

每組都輸出該組運算式的運算結果,輸出結果保留兩位小數。

樣例輸入

2
1.000+2/4=
((1+2)*5+1)/4=

樣例輸出

1.50
4.00
#include<stdio.h>
#include<string.h>
#include<stack>
#include<ctype.h>
#include<stdlib.h>
using namespace std;
int priority(char c)
{
	if(c=='=') return 0;
	if(c=='+') return 1;
	if(c=='-') return 1;
	if(c=='*') return 2;
	if(c=='/') return 2;
	return 0;
}
void compute(stack<double>& num,stack<char>& ch)
{
	double b=num.top();
	num.pop();
	double a=num.top();
	num.pop();
	switch(ch.top())
	{
		case'+':
			num.push(a+b);
			break;
		case'-':	
			num.push(a-b);
			break;
		case'*':
			num.push(a*b);
			break;
		case'/':
			num.push(a/b);
			break;
	}
	ch.pop();
}
int main()
{
	int n;
	char str[1005];
	stack<double> num;
	stack<char> ch;
	scanf("%d",&n);
	while(n--)
	{	
		scanf("%s",&str);
		int len=strlen(str);
		for(int i=0;i<len;i++) 
		{
			if(isdigit(str[i]))
			{
				double n=atof(&str[i]);
				while(i<len&&(isdigit(str[i])||str[i]=='.'))
					i++;
				i--;
				num.push(n);
			}
			else
			{
				if(str[i]=='(')
					ch.push(str[i]);
				else if(str[i]==')')
				{
					while(ch.top()!='(')	
						compute(num,ch);
					ch.pop();		
				}
				else if(ch.empty()||priority(str[i])>priority(ch.top()))
					ch.push(str[i]);
				else 
				{
					while(!ch.empty() && priority(str[i])<=priority(ch.top()))
						compute(num,ch);
					ch.push(str[i]);
				}
			}
		}
		ch.pop();
		printf("%.2f\n",num.top());
	}
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章