读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。
Input
测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。
Output
对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。
Sample Input
1 + 2 4 + 2 * 5 - 7 / 11 0
Sample Output
3.00
13.36
后缀表达式:在算术表达式中运算符在操作数的后面。
注意:1.已经考虑了运算符的优先级;2.没有括号,只有操作数和运算符;3.越放在前面的运算符越优先执行。
一、将算术表达式(中缀表达式)转化为后缀表达式
4+2*5-7/11---------->4 2 5 * + 7 11 / -
二、后缀表达式求值
先乘除(for循环)后加减(while循环)
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <stack>
using namespace std;
char str[210];
int change(char a)
{
if(a == '+') return 1;
if(a == '-') return 2;
if(a == '*') return 3;
if(a == '/') return 4;
return 0;
}
int cmp(int x,int y)//比较优先级大小
{
if(x ==1 || x == 2)
x = 1;
else
x = 2;
if(y == 1 || y == 2)
y = 1;
else
y = 2;
if(x >= y)
return 1;
return 0;
}
int main()
{
stack<double>p;
stack<int>q;
while(!p.empty()) p.pop();
while(!q.empty()) q.pop();
while(gets(str))
{
int n = strlen(str);
if(n == 1 && str[0] == '0')
break;
for(int i = 0; i < n; i++)
{
double s;
if(str[i] == ' ')
continue;
else if(str[i] >= '0' && str[i] <= '9')
{ {
s = 0;
while(str[i] >= '0' && str[i] <= '9')//保留多位的整数
{
s = s*10 + str[i] - '0';
i++;
}
p.push(s);
}
else
{
if(q.empty())
{
int temp = change(str[i]);
q.push(temp);
continue;
}
else
{
int num1 = change(str[i]);
int num2 = q.top();
while(cmp(num2,num1))//如果栈里优先级比str【i】高,弹出运算,否则将str【i】压入栈/********************重点***********************/
{
q.pop();
double a = p.top(); p.pop();
double b = p.top(); p.pop();
switch(num2)
{
case 1:
p.push(b+a);
break;
case 2:
p.push(b-a); //b在前,a再后
break;
case 3:
p.push(b*a);
break;
case 4:
p.push(b/a);
break;
}
if(q.empty())
break;
else
num2 = q.top();
}
q.push(num1);
}
}
}
while(!q.empty())//再剩下的都是+、-,直接就可运算
{
double a = p.top(); p.pop();
double b = p.top(); p.pop();
int x = q.top(); q.pop();
switch(x)
{
case 1:
p.push(b+a);
break;
case 2:
p.push(b-a);
break;
case 3:
p.push(b*a);
break;
case 4:
p.push(b/a);
break;
}
}
printf("%.2f\n",p.top());
}
}