计算器的功能:
加+ 减- 乘* 除/ 逻辑或|| 逻辑与&& 逻辑非!
基本原理:
设计两个栈来分别储存运算符和数字,运算符栈用‘#’表示开始与结束 让运算符和数字依次入栈 出栈规则:当前入栈的运算符比栈顶的运算符优先级低 例: 12+5*(2+3)*6/2-4 ![在这里插入图片描述](https://img-blog.csdnimg.cn/20200624154806664.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTc2OTA1OA==,size_16,color_FFFFFF,t_70)
![在这里插入图片描述](https://img-blog.csdnimg.cn/2020062415491581.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTc2OTA1OA==,size_16,color_FFFFFF,t_70)
代码实现
#include
#include
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int OperatorPri(char opt)//将优先级量化便于比较
{
switch(opt)
{
case '#': return 0;
case ')': return 1;
case '|':
case '&': return 2;
case '-':
case '+': return 3;
case '*':
case '/': return 4;
case '!': return 5;
case '(': return 6;
default: return -1;
}
}
int PreOrder(char opt1,char opt2)//比较两个运算符的优先级
{
int i = OperatorPri(opt1);
int j = OperatorPri(opt2);
if(opt2=='(') //( )内的 + - * / 还能进栈但是 + - * / 对应的数字小于 ( 对应的数字 所以把这里设置成 1 让()内的 + - * / 可以进栈
return 1;
if(i==-1||j==-1)
return -1;
if(i>j)
return 1;
else if(i==j)
return 0;
else
return -1;
}
bool isOpr(char *p) //判断运算公式中的字符是不是数字
{
if(*p>='0'&&*p
num = 10*num + (*p-'0');
p++;
}
p--; //为了防止后面while循环中的p++跳过了运算符 !!!!!!!!!
return p;
}
int express(int e1,int e2,char opt) //运算
{
cout
int x; //用来储存 express(e1,e2,opt) 要不然输出两边 cout
p = getNum(p,e);
opr.push(e);
cout
opt.push(*p);
cout
opr.push(e2);
cout
c = opt.top(); //先判断这是否是个空括号
if(c!='(')
{
c = opt.top();
opt.pop();
cout
opt.pop();
cout
opr.push(e2);
cout
opr.push(e2);
cout |