#include<iostream.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX_SIZE 100
int IStack[MAX_SIZE];
char CStack[MAX_SIZE];
int i,c;
void Calculate1()
{
int x1,x2,x;
char p;
p=CStack[--c];
x2=IStack[--i];
x1=IStack[--i];
switch(p)
{
case '+': x=x1+x2; break;
case '-': x=x1-x2; break;
case '*': x=x1*x2; break;
case '/':
if(!x2)
{
cout<<"0不能做被除数!"<<endl;
exit(0);
}
x=x1/x2; break;
}
IStack[i++]=x;
}
bool legal(char *f)
{
i=c=0;
char *p=f;
while(*p!='\0')
{
switch(*p)
{
case '(':
CStack[c++]='('; break;
case ')':
if(c&&CStack[c-1]=='(') c--;
else return false;
break;
}
p++;
}
if(c==0) return true;
else return false;
}
void Erjinzhi(int a)
{
int b[50],i=0,c;
while(a)
{
b[i]=a%2;
a=a/2;
i++;
}
for(c=i-1;c>=0;c--)
printf("%d",b[c]);
}
void Calculate2(char *f)
{
int Number;
i=c=0;
char *p=f;
while(*p!='\0')
{
switch(*p)
{
case '(':
CStack[c++]='(';
p++;
break;
case ')':
while(CStack[c-1]!='(')
Calculate1();
c--;
p++;
break;
case '+':
case '-':
case '*':
case '/':
if(CStack[c-1]=='+'||CStack[c-1]=='-')
CStack[c++]=*p;
else
{
if(i<1)
{
cout<<"运算符输入错误!"<<endl;
exit(0);
}
else if(i==1)
CStack[c++]=*p;
else if(i>1)
{
if(CStack[c-1]!='(')
{
do
{
Calculate1();
}while(CStack[c-1]!='(');
}
CStack[c++]=*p;
}
}
p++;
break;
default:
Number=0;
do
{
Number=10*Number+*p-'0';
p++;
}while(*p>='0'&&*p<='9');
IStack[i++]=Number;
}
}
printf("结果为:\n");
printf("-----------\n");
printf("十进制:%d\n",IStack[0]);
printf("二进制:");
Erjinzhi(IStack[0]);
printf("\n");
printf("八进制:%o\n",IStack[0]);
printf("十六进制:%x\n",IStack[0]);
printf("-----------\n");
}
void main()
{
char a[MAX_SIZE],*f;
int i;
cout<<"\t\t\t\t|表达式求值|"<<endl;
cout<<"请输入表达式:";
la: cin>>a;
for(i=MAX_SIZE-1;i>0;i--)
a[i]=a[i-1];
a[0]='(';
a[strlen(a)]=')';
f=a;
if(!legal(f))
{
cout<<"表达式错误,请重新输入:";
goto la;
}
Calculate2(f);
}