标签:style blog io ar os 使用 sp on 数据
比如输入:“1+2/4=”,程序就输出1.50(结果保留两位小数)
数据保证除数不会为0
输出
每组都输出该组运算式的运算结果,输出结果保留两位小数。
((1+2)*5+1)/4=
样例输出
1.504.00
来源
数据结构课本例题改进
上传者
张云聪
题目大意:给你一个计算表达式,求出最终结果。
思路:用两个栈来分别存数和操作符, 遇到‘(‘,操作符入栈,遇到‘)‘,计算括号内的
式子。遇到‘+‘、‘-‘、‘*‘、‘/‘就比较当前运算符与栈中运算符的优先级,大于等于于栈
中优先级就计算,否则就入栈,留待下次计算。最后计算栈中剩下优先级低的相应式子
#include<iostream>
#include<algorithm>
#include<stack>
#include<string>
#include<cstring>
#include<cstdio>
using namespace std;
stack<double> num;
stack<char> oper;
char a[1010],buf[1010];
int CmpValue(char op)
{
if(op=='(' )
return 0;
if(op=='+' || op=='-')
return 1;
if(op=='*' || op=='/')
return 2;
}
void calc()
{
double x,y;
char op;
if(num.size()>=2 && !oper.empty())
{
y = num.top();
num.pop();
x = num.top();
num.pop();
op = oper.top();
if(op=='+')
num.push(x+y);
else if(op=='-')
num.push(x-y);
else if(op=='*')
num.push(x*y);
else if(op=='/')
num.push(x/y);
oper.pop();
}
}
int main()
{
int N;
cin >> N;
while(N--)
{
memset(a,0,sizeof(a));
memset(buf,0,sizeof(buf));
scanf("%s",a);
int i = 0;
while(1)
{
if(isalnum(a[i]))
{
double d;
sscanf(a+i,"%lf",&d);
num.push(d);
while(isalnum(a[i]) || a[i]=='.')
i++;
}
char c = a[i++];
if(c=='=' || c=='\0')
break;
if(c=='(')
oper.push(c);
else if(c==')')
{
while(!oper.empty())
{
if(oper.top()=='(')
{
oper.pop();
break;
}
calc();
}
}
else
{
while(!oper.empty() && CmpValue(c) <= CmpValue(oper.top()))
{
calc();
}
oper.push(c);
}
}
while(!oper.empty())
calc();
printf("%.2lf\n",num.top());
while(num.empty())
num.pop();
}
return 0;
}
标签:style blog io ar os 使用 sp on 数据
原文地址:http://blog.csdn.net/lianai911/article/details/41908933