链接在此:https://vjudge.net/contest/291337#problem/D
中文题解:
读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。
Input
测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。
Output
对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。
Sample Input
1 + 2
4 + 2 * 5 - 7 / 11
0
Sample Output
3.00
13.36
看这道题一头雾水,完全没有思路,看别人的代码,用栈是一种很好的思路
解法:把第一个数压入栈,接下来根据每次的运算符来确定操作方法,若是加或减,把输入的x或-x继续压入栈中,若是乘或除,则将运算符前面的数字取出,也就是栈顶的元素,运算后继续压入栈内,这样输入结束之后就可以直接将栈内的元素加起来即是所求结果
代码在此:
#include<cstdio>
#include<iostream>
#include<queue>
#include<stack>
#include<cstring>
using namespace std;
int main()
{
double a;
char c;
stack<double>s;
while(cin>>a)
{
double x;
s.push(a);
if(getchar()!=' ')break;
while(1)
{
c=getchar();
cin>>a;
if(c=='+')
{
s.push(a);
}
else if(c=='-')
{
s.push(-a);
}
else if(c=='*')
{
x=s.top();
s.pop();
s.push(x*a);
}
else if(c=='/')
{
x=s.top();
s.pop();
s.push(x/a);
}
if(getchar()!=' ')break;
}
double sum=0;
while(!s.empty())
{
sum+=s.top();
s.pop();
}
printf("%.2lf\n",sum);
}
}