数据结构C语言用栈实现表达式计算器,求完整源代码,邮箱601816948@qq.com
用户输入一个完整的四则运算表达式,程序能够求出表达式的值。要求能够处理括号、正负符号、加减乘除四则运算等。
基本要求:
括号处理、正负符号处理、加减乘除四则运算以及浮点数在表达式中的处理。
应用:
表达式合法性检查、栈的应用、优先级别的判定
谢谢!
邮箱601816948@qq.com 展开
#include<iostream>#include<sstream>#include<stack>#include<string>using namespace std;float stringToNum(const string& str) { istringstream iss(str); float num; iss >> num; return num; }
int In(string c){ if(c == "+" || c == "-" || c == "*" || c == "/" || c == "(" || c == ")"|| c == "#") return 1; else return 0;}
string procede(string op1,string op2){ if(op1 == "+" && (op2 == "*"||op2 =="/"||op2 =="(")) return "<"; if(op1 == "+" && (op2 == "+"||op2 =="-"||op2 ==")"||op2 =="#")) return ">"; if(op1 == "-" && (op2 == "*"||op2 =="/"||op2 =="(")) return "<"; if(op1 == "-" && (op2 == "+"||op2 =="-"||op2 ==")"||op2 =="#")) return ">"; if(op1 == "*" && op2 =="(") return "<"; if(op1 == "*" && (op2 == "+"||op2 =="-"||op2 =="*"||op2 =="/"||op2 ==")"||op2 =="#")) return ">"; if(op1 == "/" && op2 =="(") return "<"; if(op1 == "/" && (op2 == "+"||op2 =="-"||op2 =="*"||op2 =="/"||op2 ==")"||op2 =="#")) return ">"; if(op1 == "(" && op2 ==")") return "="; if(op1 == "(" && (op2 =="+"||op2 =="-"||op2 =="*"||op2 =="/"||op2 =="(")) return "<"; if(op1 == ")" && (op2 =="+"||op2 =="-"||op2 =="*"||op2 =="/"||op2 ==")"||op2 =="#")) return ">"; if(op1 == "#" && (op2 =="+"||op2 =="-"||op2 =="*"||op2 =="/"||op2 =="("||op2 =="#")) return "<";}
float operate(float a,string op,float b){ if(op == "+") return a+b; if(op == "-") return a-b; if(op == "*") return a*b; if(op == "/") return a/b;}
int evaluateExpression(){ float num1,num2; stack<float> OPND; //存放运算数 stack<string> OPTR; //存放操作符 OPND.empty(); OPTR.empty(); OPTR.push("#"); std::string c; cin>>c; while(c != "#" || OPTR.top() != "#") { if(!In(c))//不是运算符进栈 { OPND.push(stringToNum(c)); cin>>c; } else { // cout<<procede(OPTR.top(),c)<<endl; if(procede(OPTR.top(),c) == "<") { OPTR.push(c); cin>>c; } else if(procede(OPTR.top(),c) == "=") { OPTR.pop(); cin>>c; } else if(procede(OPTR.top(),c) == ">") { string op = OPTR.top(); OPTR.pop(); num1 = OPND.top(); OPND.pop(); num2 = OPND.top(); OPND.pop();
OPND.push(operate(num2,op,num1)); } } } if(!OPND.empty()) return OPND.top(); else return 0;}
int main(){ while(1) { cout<<evaluateExpression()<<endl; } system("pause"); return 0;}