遞歸計算逆波蘭表達式

需求

計算逆波蘭表達式(後綴表達式)

逆波蘭表達式又叫做後綴表達式。在通常的表達式中,二元運算符總是置於與之相關的兩個運算對象之間,這種表示法也稱爲中綴表示。波蘭邏輯學家J.Lukasiewicz於1929年提出了另一種表示表達式的方法,按此方法,每一運算符都置於其運算對象之後,故稱爲後綴表示。

正常的表達式 逆波蘭表達式
a + b a b +
a + (b - c) a b c - +
a + (b - c) * d a b c - d * +
a + d * (b - c) a d b c - * +
a = 1 + 3 a = 1 3 +

測試數據

35.0 24.0 + 12.0 11.0 + *

下面寫的代碼是使用了freopen的,可以在f盤建一個叫data.txt的文件把數據放進去,代碼會直接讀取,如果想手動輸入就把freopen那一行註釋掉。

代碼

#include <vector>
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;
double exp(vector<string>& v)
{
    string s = v.back();
    v.pop_back();
    const char* c = s.data();
    switch(c[0]) {
    case '+':
        return exp(v) + exp(v);
    case '-':
        return exp(v) - exp(v);
    case '*':
        return exp(v) * exp(v);
    case '/':
        return exp(v) / exp(v);
    default:
        return atof(c);
    }
}
int main()
{

    static vector<string> v;
    freopen("f:\\data.txt", "r", stdin);
    string s;
    while(cin >> s) {
        v.push_back(s);
    }
    cout << exp(v) << endl;
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章