问题描述
- 求解,用以下代码编一个计算器为什么结果为nan?
-
#include
using namespace std;
#include"stack.h"
#include
//TLinkStack s0;
TLinkStack v0;
char *expr = new char[1000];
char *ex = new char[1000];int isp(char ch)//in stack priority
{switch(ch)
{
case'#' :return 0;
case'(' :return 1;
case'*' :return 5;
case'/' :return 5;
case'%' :return 5;
case'+' :return 3;
case'-' :return 3;
case')' :return 6;
}
}
int icp(char ch)//in coming priority
{switch(ch)
{
case'#' :return 0;
case'(' :return 6;
case'*' :return 4;
case'/' :return 4;
case'%' :return 4;
case'+' :return 2;
case'-' :return 2;
case')' :return 1;
}}void postfix(char *e)
{TLinkStack s;char ch='#',ch1,op;
int i=0,a=0,b,t=0,k=0;
int j=1;
s.push(ch);
int length=strlen(e);
while((!s.Isempty())&&(i<length))
{ch=e[i];
if(isdigit(ch))
{
expr[k]=ch; k++;
ex[t]=ch; t++;
i++;}//take figures in the stack
else{if(isdigit(expr[k-1]))
{expr[k]=' ';k++;}
s.getTop(ch1);
if(isp(ch1)<icp(ch)){
s.push(ch);
i++;}//外部优先级高于内部优先级进栈else if(isp(ch1)>icp(ch)) {
s.pop(op);
if(op!='#') {
expr[k]=op;k++;
ex[t]=op;t++;
}
}//外部优秀级低于内部优先级退栈else {s.pop(op);
if(op=='(') { i++;
}}
}
}
cout<<ex<<endl;
};void pre(int i)
{int length=strlen(expr);
int a=0,b=0;
{if(isdigit(expr[i]))
{b=expr[i]-48;
a=a*10+b; }
else if(expr[i]=' ')
{v0.push(a);
a=0;
b=0;
}
}
}bool getfigure(double &left,double &right)
{if(v0.Isempty()==true){return false;
}v0.pop(right);if(v0.Isempty()==true){return false;
}v0.pop(left);
return true;
}void calculator()
{
int result,length=strlen(expr);
double x,y,value;
for(int i=0;i<length;i++)
{pre(i);
if(expr[i]='+')
{if(getfigure(x,y))
{value=x+y;v0.push(value);}}if(expr[i]='-')
{if(getfigure(x,y))
{value=x-y;v0.push(value);}}if(expr[i]='*')
{if(getfigure(x,y))
{value=x*y;v0.push(value);}}if(expr[i]='/')
{if(getfigure(x,y))
{value=x/y;v0.push(value);}}
}
v0.getTop(value);
cout<<"the result is"<<value;
}