贴一个我写的RPN算法,欢迎交流
本帖最后由 qq1205470086 于 2014-1-23 23:50 编辑大一寒假在家自学数据结构,刚好看到小甲鱼老师发布的这个教程,很开心!
刚看到后缀表达式这个地方,贴一个我写的代码,欢迎交流!
希望鱼C论坛越办越好!!!#include <string>
#include <sstream>
#include <stack>
#include <map>
#include <iostream>
#include <algorithm>
#include <functional>
using namespace std;
//中缀表达式转后缀表达式
void convert(const char* source, string& result){
map<char,int> priority;
priority['+']=1; priority['-']=2; priority['*']=3; priority['/']=4;
string sou(source),res(result),str;
stringstream strstream(sou);
stack<char> st;
char c;
while(strstream>>c){
if(isdigit(c)||c=='.') result.append(&c,1);
else if(c==')'){
result.append(" ");
while(st.top()!='('){
result.append(string(" ")+st.top()+string(" "));
st.pop();
}
st.pop();
}else if(c=='('){ st.push(c); result.append(" ");}
else{
if(!st.empty()&&priority>=priority){
result.append(string(" ")+st.top()+string(" "));
st.pop();
}
st.push(c);
result.append(" ");
}
}
while(!st.empty()){
result.append(string(" ")+st.top());
st.pop();
}
stringstream restream(result);
result.clear();
while(restream>>str) result.append(str+" ");
}
//计算后缀表达式
double calc(const char* expr){
string str(expr);
stringstream exprstream(str);
stack<double> st;
string c;
while(exprstream>>c){
if(c!="+"&&c!="-"&&c!="*"&&c!="/") st.push(atof(c.c_str()));
else{
double x,y;
x=st.top(); st.pop();
y=st.top(); st.pop();
if(c=="+") st.push(y+x);
else if(c=="-") st.push(y-x);
else if(c=="*") st.push(y*x);
else st.push(y/x);
}
}
return st.top();
}
int _tmain(int argc, _TCHAR* argv[]){
string str,res;
getline(cin,str);
if(!str.empty()){
str.erase(remove_if(str.begin(),str.end(),bind2nd(std::equal_to<char>(),' ')),str.end());
convert(str.c_str(),res);
cout<<res<<endl;
cout<<calc(res.c_str())<<endl;
}
return 0;
} 这个用户名可不可以改。。。我以为只是登陆用的呢。。。 qq1205470086 发表于 2014-1-24 00:12 static/image/common/back.gif
这个用户名可不可以改。。。我以为只是登陆用的呢。。。
论坛不支持修改用户名哦~ 小甲鱼 发表于 2014-1-24 01:02 static/image/common/back.gif
论坛不支持修改用户名哦~
本尊驾到,不胜荣幸{:1_1:}
教程非常不错{:1_1:} qq1205470086 发表于 2014-1-24 01:06 static/image/common/back.gif
本尊驾到,不胜荣幸
教程非常不错
{:7_157:}大家一起学习共勉! 很好很好啊 很好很好啊 看了下你的后缀表达式的计算,逻辑很清晰,确实不错。不过,建议你写程序的时候,多写些注释,方便其他人读你的程序,也方便你以后再看自己写的东西。 故乡的风 发表于 2014-1-25 03:54 static/image/common/back.gif
看了下你的后缀表达式的计算,逻辑很清晰,确实不错。不过,建议你写程序的时候,多写些注释,方便其他人读 ...
好的,谢谢 感谢楼主分享 激动人心,无法言表! 学习了
很好的帖子 太长了吧,不过我最喜欢这种帖子了,好东东 楼主好厉害啊! 谢谢楼主分享!!!!!!!! 谢谢LZ分享 回帖是一种美德 我也才刚刚学习数据结构,收藏先!!!!!! 谢谢喽组分享 学习一下。。。
页:
[1]
2