c++ 手写计算器
数据结构课上老师布置了个作业,让自己写一个计算器,要求支持小数运算及括号,早上刷牙时构思了一下,发现可以用两个栈来实现。 其中,一个栈用来存运算符,一个栈用来存运算的数,利用栈将输入的中缀表达式转化为计算器好识别的后缀表达式,当存运算符的栈中pop出运算符时,就取存运算数的栈上的前两个进行运算,在将运算结果压入栈中。 具体实现代码如下 #include<iostream> #include<cstring> #include<stack> using namespace std; stack<double> num; stack<char> sign; void calc(char c){ double a,b; a=num.top(); num.pop(); b=num.top(); num.pop(); if(c=='+') num.push(a+b); else if(c=='-') num.push(b-a); else if(c=='*') num.push(a*b); if(c=='/') num.push(b/a); } double solve(string s){ char top; double ans=0; char c; double n=0; int len=s.length(); double m=1,d=0; for(int i=0;i<len;i++