例題:逆波蘭表達式
逆波蘭表達式是一種把運算符前置的算術表達式,例如普通的
表達式2 + 3的逆波蘭表示法為+ 2 3。逆波蘭表達式的優點是運算
符之間不必有優先級關系,也不必用括號改變運算次序,例如(2 +
3) * 4的逆波蘭表示法為* + 2 3 4。本題求解逆波蘭表達式的值,
其中運算符包括+ - * /四個
代碼如下:
#include <iostream> #include<cstdlib> using namespace std; double Bolan(); int main() { double s=Bolan(); cout<<s<<endl; return 0; } double Bolan() { char s[100]; cin>>s; switch(s[0]){//取字符第一個 case '+':return Bolan()+Bolan(); case '-':return Bolan()-Bolan(); case '*':return Bolan()*Bolan(); case '/':return Bolan()/Bolan(); default:return atof(s); break; } }