给定一个字符串表达式s,计算其值(使用string和stack实现)

来源:互联网 发布:疾病自测软件 编辑:程序博客网 时间:2024/04/30 22:30
<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>

1 0