您的位置:首页 > 其它

利用栈做的中缀计算器雏形

2016-02-17 12:11 246 查看
#include<iostream>
#include<cstdlib>
#include<stdio.h>
#include<cstring>
#include<queue>
#include<algorithm>
#include<stack>
using namespace std;
stack<double>num;//有关数字的栈
stack<char>op;//有关运算符的栈
bool Is_op_character(char ch)//判断是否是运算符
{
return ch=='+'||ch=='-'||ch=='*'||ch=='/'||ch=='='||ch==' '||ch=='('||ch==')';
}
int operation(char ch)//对数字的操作
{
double a,b;
switch (ch)
{
case '+':
{
if(num.empty())
{
cout<<"表达式不规范\n";
return 0;
}
a=num.top();
num.pop();
if(num.empty())
{
cout<<"表达式不规范\n";
return 0;
}
b=num.top();
num.pop();
num.push(a+b);
}break;
case '-':
{
if(num.empty())
{
cout<<"表达式不规范\n";
return 0;
}
a=num.top();
num.pop();
if(num.empty())
{
cout<<"表达式不规范\n";
return 0;
}
b=num.top();
num.pop();
num.push(b-a);
}break;
case '*':
{
if(num.empty())
{
cout<<"表达式不规范\n";
return 0;
}
a=num.top();
num.pop();
if(num.empty())
{
cout<<"表达式不规范\n";
return 0;
}
b=num.top();
num.pop();
num.push(a*b);
}break;
case '/':
{
if(num.empty())
{
cout<<"表达式不规范\n";
return 0;
}
a=num.top();
num.pop();
if(num.empty())
{
cout<<"表达式不规范\n";
return 0;
}
b=num.top();
num.pop();
if(a==0)
{
cout<<"除数为零"<<endl;
return 0;
}
else
num.push(b/a);
}break;
default: return 1;
}
return 1;
}
int do_in_operation(char ch)//有关运算符的操作
{
bool right=1;
switch (ch)
{
case '+':
{
while(!op.empty()&&op.top()!='(')
{
ch=op.top();
op.pop();
right=operation(ch);
}
op.push('+');
}break;
case '-':
{
while(!op.empty()&&op.top()!='(')
{
ch=op.top();
op.pop();
right=operation(ch);
}
op.push('-');
}break;
case '*':
{
while(!op.empty()&&op.top()!='+'&&op.top()!='-'&&op.top()!='(')
{
ch=op.top();
op.pop();
right=operation(ch);
}
op.push('*');
}break;
case '/':
{
while(!op.empty()&&op.top()!='+'&&op.top()!='-'&&op.top()!='(')
{
ch=op.top();
op.pop();
right=operation(ch);
}
op.push('/');
}break;
case ')':
{
while(!op.empty()&&op.top()!='(')
{
ch=op.top();
op.pop();
right=operation(ch);
}
if(!op.empty())
op.pop();
else
{
cout<<"表达式不规范\n";
return 1;
}
}break;
case '(':
{
op.push('(');
}break;
case '=':
{
while(!op.empty())
{
ch=op.top();
op.pop();
right=operation(ch);
}
cout<<num.top()<<endl;
}break;
}
return right;
}
int main()
{
char ch;
char number[15];
cout<<"计算器1.3------------------------------------\n支持四则运算,支持小数点后十五位的小数,支持括号,不支持负数T.T\n";
cout<<"使用方法:输入运算式,输入等号并回车后输出结果,按'#'结束程序 \n";
int i=0;
double a,b;
cin>>ch;
while(ch!='#')
{
while(ch>='0'&&ch<='9'||ch=='.')//对小数的支持
{
number[i]=ch;
i++;
number[i]='\0';
if(i>=10)
{
cout<<"输入单个数据精度过大"<<endl;
return -1;
}
cin>>ch;
if(Is_op_character(ch))
{
a=atof(number);
num.push(a);
i=0;
break;
}
}
if(do_in_operation(ch))
cin>>ch;
else break;
}
cout<<"程序即将退出\n" ;
system("pause");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: