表达式求值
时间限制:
3000 ms | 内存限制:
65535 KB
难度:
4
-
描述
-
ACM队的mdd想做一个计算器,但是,他要做的不仅仅是一计算一个A+B的计算器,他想实现随便输入一个表达式都能求出它的值的计算器,现在请你帮助他来实现这个计算器吧。
比如输入:“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
来源
- 数据结构课本例题改进
-
第一行输入一个整数n,共有n组测试数据(n<10)。
#include<algorithm>
#include<cstdio>
#include<iostream>
#include<stack>
using namespace std;
stack<double>a; //数据栈
stack<char>b; //操作符栈
int ValueCmp(char c)
{
if(c=='(')
return 0;
else if(c=='+'||c=='-')
{
return 1;
}
else if(c=='*'||c=='/')
{
return 2;
}
}
void calc()
{
double num1,num2;
char ch;
if(a.size()>=2 && !b.empty())
{
num1=a.top();
a.pop();
num2=a.top();
a.pop();
ch=b.top();
if(ch=='+')
{
a.push(num1+num2);
}
else if(ch=='-')
{
a.push(num2-num1);
}
else if(ch=='*')
{
a.push(num1*num2);
}
else if(ch=='/')
{
a.push(num2/num1);
}
b.pop();
}
}
int main()
{
int i,j;
int t;
char s[1010];
double temp;
scanf("%d",&t);
getchar();
while(t--)
{
gets(s);
i=0;
while(1)
{
if(isalnum(s[i]))
{
sscanf(s+i,"%lf",&temp);
a.push(temp);
while(isalnum(s[i]) || s[i]=='.') ++i;
}
//double d=a.top();
char ch=s[i++];
if(ch=='\0'||ch=='=') break;
if(ch=='(')
{
b.push(ch);
}
else if(ch==')')
{
while(!b.empty())
{
if(b.top()=='(')//直到栈顶为'('时停止
{
b.pop();
break;
}
else
calc() ;
}
}
else
{
int flag=ValueCmp(ch);
while(!b.empty() && ValueCmp(ch)<=ValueCmp(b.top()))
{
calc();
}
b.push(ch);
}
}
while(!b.empty()) calc();
printf("%.2lf\n",a.top());
//int flag=a.empty();
a.pop();
//printf("%d ",flag);
/*while(a.empty())
{
a.pop();
}*/
}
return 0;
}