給定一個字串表示式s,計算其值(使用string和stack實現)
阿新 • • 發佈:2019-01-23
<span style="font-size:18px;">toPosfix函式將中綴表示式轉換為字尾表示式,calculatePosfix函式計算字尾表示式的值。 #include <iostream> #include <stack> #include <string> using std::string; using std::stack; using std::cout; using std::cin; using std::endl; string &toPosfix(string &s, string &format) {//中綴表示式轉字尾表示式,並且可以計算小數 stack<char> sta; string numbers{ "0123456789." }; string signl{ "+-" }; string signh{ "*/" }; string numbe;//判斷某數是否為多位數 bool flag = false; for (const char &ch : s) { if (ch == ' ') continue; //判斷這是幾位數 if (numbers.find(ch) != string::npos) { flag = true; numbe.push_back(ch); continue; } else if (flag) { flag = false; format.insert(format.end(), numbe.begin(), numbe.end()); numbe.clear(); format.push_back(' '); } //判斷ch什麼符號 if (ch == '(') sta.push(ch); else if (signl.find(ch) != string::npos) {//如果進棧的是“+-”運算子 while (!sta.empty() && sta.top() != '(') { format.push_back(sta.top()); format.push_back(' '); sta.pop(); } sta.push(ch); } else if (signh.find(ch) != string::npos) { while (!sta.empty() && sta.top() != '('&&signh.find(sta.top()) != string::npos) { format.push_back(sta.top()); format.push_back(' '); sta.pop(); } sta.push(ch); } else if (ch == ')') { //ch==')' while (!sta.empty() && sta.top() != '(') { format.push_back(sta.top()); format.push_back(' '); sta.pop(); } sta.pop(); } } if (!numbe.empty()) { format.insert(format.end(), numbe.begin(), numbe.end()); numbe.clear(); format.push_back(' '); } while (!sta.empty()) { format.push_back(sta.top()); format.push_back(' '); sta.pop(); } return format; } double calculatePosfix(string &s) { stack<double> sta; double sum = 0; string numbers{ "0123456789." }; string sign{ "+-*/" }; string numbe; double num1, num2; for (const char &ch : s) { if (ch == ' '&&!numbe.empty()) { double digit = stod(numbe); sta.push(digit); numbe.clear(); } if (numbers.find(ch) != string::npos) numbe.push_back(ch); else if (sign.find(ch) != string::npos) { num2 = sta.top(), sta.pop(); num1 = sta.top(), sta.pop(); double ans = 0; switch (ch) { case '+': ans += num1 + num2; break; case '-': ans += num1 - num2; break; case '*': ans += num1*num2; break; case '/': ans += num1 / num2; break; } sta.push(ans); } } while (!sta.empty()) { sum += sta.top(); sta.pop(); } return sum; } double calculateinfix(string &s) { string format; toPosfix(s, format); return calculatePosfix(format); } int main() { string s{ "9.8*2+3-(2*3-6+5)" }; cout << calculateinfix(s) << endl; cout << 9.8 * 2 + 3 - (2 * 3 - 6 + 5) << endl; return 0; }</span>