一道面试题,如何用c语言求24点
如题。输入4个数a b c d,如果能是24点,打印出步骤,否则输出"no answer"
我写了一个,有些问题
24.cpp
#include<iostream>#include<algorithm>#define MAX 0xFFFFFFFFusing namespace std;void print(int const& a){ cout<<a<<' ';}enum OPERATOR {ADD,SUB,SUB2,MUL,DIV,DIV2,TOTAL};char trans(OPERATOR i){ switch(i){ case ADD: return '+'; case SUB: case SUB2: return '-'; case MUL: return '*'; case DIV: case DIV2: return '/'; }}double cal(double a,double b,int mode){ switch(mode){ case ADD: //cout<<a<<'+'<<b; return a+b; case SUB: //cout<<a<<'-'<<b; return a-b; case SUB2: //cout<<b<<'-'<<a; return b-a; case MUL: //cout<<a<<'*'<<b; return a*b; case DIV: //cout<<a<<'/'<<b; if(b==0)return MAX; return a/b; case DIV2: //cout<<b<<'/'<<a; if(a==0)return MAX; return b/a; }}void can24(int p[4]){ sort(p,p+4); do{ for(int i=ADD;i<TOTAL;++i){ for(int j=ADD;j<TOTAL;++j){ for(int k=ADD;k<TOTAL;++k){ if(cal(cal(cal(p[0],p[1],i),p[2],j),p[3],k) == 24){ if(i == SUB2 || i==DIV2){ cout<<"step 1:"<<p[1]<<trans((OPERATOR)i)<<p[0]<<endl; }else{ cout<<"step 1:"<<p[0]<<trans((OPERATOR)i)<<p[1]<<endl; } if(j==SUB2 || j==DIV2){ cout<<"step 2:"<<p[2]<<trans((OPERATOR)j)<<cal(p[0],p[1],i)<<endl; } else{ cout<<"step 2:"<<cal(p[0],p[1],i)<<trans((OPERATOR)j)<<p[2]<<endl; } if(k==SUB2 || k==DIV2){ cout<<"step 3:"<<p[3]<<trans((OPERATOR)k)<<cal(cal(p[0],p[1],i),p[2],j)<<endl; } else{ cout<<"step 3:"<<cal(cal(p[0],p[1],i),p[2],j)<<trans((OPERATOR)k)<<p[3]<<endl; } //system("pause"); return; } if( cal(cal(p[0],p[1],i),cal(p[2],p[3],j),k) == 24){ if(i==SUB2 || i==DIV2){ cout<<"step 1:"<<p[1]<<trans((OPERATOR)i)<<p[0]<<endl; } else{ cout<<"step 1:"<<p[0]<<trans((OPERATOR)i)<<p[1]<<endl; } if(i==SUB2 || i==DIV2){ cout<<"step 2:"<<p[3]<<trans((OPERATOR)j)<<p[2]<<endl; } else{ cout<<"step 2:"<<p[2]<<trans((OPERATOR)j)<<p[3]<<endl; } if(i==SUB2 || i==DIV2){ cout<<"step 3:"<<cal(p[2],p[3],j)<<trans((OPERATOR)k)<<cal(p[0],p[1],i)<<endl; } else{ cout<<"step 3:"<<cal(p[0],p[1],i)<<trans((OPERATOR)k)<<cal(p[2],p[3],j)<<endl; } //system("pause"); return; } } } } }while(next_permutation(p,p+4));}int main(){ while(1){ int p[4]; //for_each(p,p+4,print); int index=0; while(index<4){ cin>>p[index++]; } can24(p); } return 0;}