逆序波兰表达式
题目链接:https://vjudge.net/problem/OpenJ_Bailian-2694
大体思路:
利用c++超强的stl库,将数据放到栈中操作。
参考代码:
#include <algorithm>
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string>
#include<stack>
using namespace std;
int main ()
{
string s,str;
float temp=0,sum=0;
stack<float> counts;
stack<string> variable;
while(cin>>s)//输入字符到字符栈中
{
variable.push(s);
if(getchar()=='\n')
{
break;
}
}
while(!variable.empty())//将字符栈里的元素一个个出栈进行运算
{
str=variable.top();//将字符栈中的栈顶元素输出到str
variable.pop();
if(str[0]>=46&&str[0]<=57)
{
temp=stof(str,0);//将字符化为数据
counts.push(temp);//将数据入到数据栈中
}
else
{
//匹配运算符
if(str[0]=='+')//进行运算
{
sum=counts.top();
counts.pop();
sum+=counts.top();
counts.pop();
counts.push(sum);
}
if(str[0]=='-')
{
sum=counts.top();
counts.pop();
sum-=counts.top();
counts.pop();
counts.push(sum);
}
if(str[0]=='*')
{
sum=counts.top();
counts.pop();
sum*=counts.top();
counts.pop();
counts.push(sum);
}
if(str[0]=='/')
{
sum=counts.top();
counts.pop();
sum/=counts.top();
counts.pop();
counts.push(sum);
}
sum=0;//将sum初始化,方便下一次计算
}
}
printf("%f",counts.top());//输出栈顶元素,此时栈顶只有一个元素就是最终结果
return 0;
}