函数返回的的数字有公母之分?
//每组数据包含一行字符串,即24点游戏的表达式树的先序遍历序列,输入‘#’代表空树//对于每组数据,输出一行。如果不能得到24,输出“NO”。如果能得到24,按样例输出。
/*例如
+ + + 6 # # 6 # # 6 # # 6 # #
- - * 6 # # 6 # # 6 # # 6 # #
* * 1 # # 2 # # * 1 # # 2 # #
(((6+6)+6)+6)=24
(((6*6)-6)-6)=24
NO*/
//源码
#include <iostream>
#include <cctype>
#include <cstring>
#include <cstdio>
#include <string>
#include <stdlib.h>
#include <iomanip>
using namespace std;
typedef struct BiTNOde
{
char data[4];
struct BiTNOde *lchild,*rchild;
} BiTNOde,*BiTree;
void CreateBiTree(BiTree &t)
{
char ch[4];
if(!(cin>>ch))
exit(0);
if(ch[0]=='#')
t=NULL;
else
{
t=new BiTNOde;
strcpy(t->data,ch);
CreateBiTree(t->lchild);
CreateBiTree(t->rchild);
}
}
void DestoryBi(BiTree &t)
{
if(t)
{
DestoryBi(t->lchild);
DestoryBi(t->rchild);
delete t;
}
}
void PrintTraverse(BiTree t)
{
if(t)
{
if(t->lchild)
cout<<'(';
PrintTraverse(t->lchild);
cout<<t->data;
PrintTraverse(t->rchild);
if(t->rchild)
cout<<')';
}
}
double Myatoi(char *s)//(用库给的不行,用自己的试试)
{
double sum=0;
for(int i=0;s[i]!='\0';i++)
sum=sum*10+s[i]-'0';
return sum;
}
double Answer(BiTree t)
{
if(t)
{
if(!t->lchild) return Myatoi(t->data);
double x=Answer(t->lchild);
double y=Answer(t->rchild);
switch (t->data[0])
{
case'+':cout<<"x+y="<<x+y<<endl;return x+y;
case'-':cout<<"x-y="<<x-y<<endl;return x-y;
case'*':cout<<"x*y="<<x*y<<endl;return x*y;
case'/':cout<<"x/y="<<x/y<<endl;return x/y;
}
}
}
int main()
{
while(1)
{
BiTree t;
CreateBiTree(t);
if((int)Answer(t)==24){
PrintTraverse(t);
cout<<"=24"<<endl;
}
else cout<<"NO"<<endl;
DestoryBi(t);
}
return 0;
}
// / 8 # # - 3 # # / 8 # # 3 # # (这组数据过不了)
// - * 5 # # 5 # # / 8 # # 8 # #