2018-3-15
逆波兰表达式 说实话,我觉得这个题目本身就很神奇,我在想这个题目的时候在纠结输入到底应该如何处理,后来在小伙伴的提醒之下写出了答案。 我们可以在函数里面等待输入,当输入的是运算符的时候,我会等待输入两个数字来进行运算,如果输入的还是运算符,我们可以继续等待,直至输入数字,返回结果与相应的运算符进行运算。
#include<iostream> #include<cstring> #include<cmath> #include<cstdio> using namespace std; char x[10]; double dfs(){ cin>>x; switch(x[0]){ case '+':{ return dfs()+dfs(); break; } case '-':{ return dfs()-dfs(); break; } case '*':{ return dfs()*dfs(); break; } case '/':{ return dfs()/dfs(); break; } default: return atof(x); } } int main(){ printf ("%f\n",dfs()); return 0; }