您的位置:首页 > 其它

nyoj35——表达式求值

2017-01-15 13:43 363 查看


这道题是一道很好的数据结构题目,会用到栈,需要弄清楚后缀表达式。

#include <stack>
#include <stdio.h>
#include <ctype.h>
#include <string.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>& 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();
}

int main()
{
int z;
char str[1005];
stack<double> Num;
stack<char> Op;
scanf("%d",&z);
while(z--)
{
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] == '(')//如果是左括号
Op.push(str[i]);//直接入栈
else if(str[i] == ')')//如果是右括号
{
while(Op.top()!='(')//将运算符栈里面的运算符弹出来,直到为左括号结束
compute(Num,Op);//进行运算
Op.pop();//将左括号弹出
}
else if(Op.empty() || priority(str[i])>priority(Op.top()))//如果运算符栈为空或者当前运算符的优先级大于栈顶运算符的优先级,直接入栈
Op.push(str[i]);
else
{
while(!Op.empty() && priority(str[i])<=priority(Op.top()))//如果栈不为空且当前运算符的优先级小于或等于栈顶运算符的优先级,先将栈里面的运算符进行运算
compute(Num,Op);
Op.push(str[i]);//然后入栈
}
}
}
Op.pop();
printf("%.2f\n",Num.top());
Num.pop();
}
return 0;
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: