1785: 表达式求值
题目描述
实现输入一个表达式求出它的值的计算器,比如输入:“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 <stdlib.h>
#include <ctype.h>
#include <stack>
using namespace std;
int priority(char c)//运算符优先级
{
if(c=='=') return 0;
if(c=='+'||c=='-') return 1;
if(c=='*'||c=='/') return 2;
return 0;//最后一定要return 0,因为也要判断'(' 的优先级
}
void answer(stack<double>& Num,stack<char>& Op)//进行四则运算
{
double b=Num.top();
Num.pop();
double a=Num.top();
Num.pop();
switch(Op.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;
}
Op.pop();
}
void work(char *s)
{
stack<double> Num;//存放操作数
stack<char> Op;//存放操作符
int i,l;
double n;
l=strlen(s);
for(i=0;i<l;i++)
{
if(isdigit(s[i]))//isdigit,判断是否为数字,被包含在头文件 #include <stype.h>中
{
n=atof(&s[i]);
/*头文件:#include <stdlib.h>
函数 atof() 用于将字符串转换为双精度浮点数(double),其原型为:
double atof (const char* str); */
while(i<l && (isdigit(s[i]) || s[i]=='.'))
i++;
i--;
Num.push(n);
}
else
{
if(s[i]=='(')
Op.push(s[i]);
else if(s[i]==')')
{
while(Op.top()!='(')
answer(Num,Op);
Op.pop();
}
else if(Op.empty() || priority(Op.top())<priority(s[i]))
Op.push(s[i]);
else
{
while(!Op.empty() && priority(Op.top())>=priority(s[i]))
answer(Num,Op);
Op.push(s[i]);
}
}
}
printf("%.2lf\n",Num.top());
Num.pop();
Op.pop();
}
int main()
{
int t;
char s[1000];
scanf("%d",&t);
while(t--)
{
scanf("%s",s);
work(s);
}
return 0;
}