对于24点游戏,最难的在于其算法,穷举算法是将一切可能性都计算出,所以还得好好学习这个算法。
#include<iostream>
#include<stdlib.h>
using namespace std;
class Dian
{
public:
int division(int p,int q);
int judge(int a,int b,int c);
char print(int c);
void menu();
int ceshi();
};
int Dian::division(int p,int q)
{
if(q==0){
cout<<"分母不能为0"<<endl;
}
if(p%q==0) return p/q;
else
return 100000;
}
int Dian::judge(int a,int b,int c)
{
int s;
switch(c)
{
case 1:s=a+b;break;
case 2:s=a-b;break;
case 3:s=a*b;break;
case 4:s=division(a,b);break;
}
return s;
}
char Dian::print(int c)
{
if(c==1) cout<<"+";
else if(c==2) cout<<"-";
else if(c==3) cout<<"*";
else cout<<"/";
return 0;
}
int Dian::ceshi()
{
int m;
cout<<"您是否继续进行24点游戏,继续请输入1,退出请按0:";
cin>>m;
if(m==1){
system("cls");
return 1;}
else return 0;
}
void Dian::menu()
{
cout<<"***************************************"<<endl;
cout<<" 欢迎来到24点小游戏"<<endl;
cout<<"***************************************"<<endl;
cout<<"*******1.自己设置四个数字**************"<<endl;
cout<<"*******2.系统随机设置******************"<<endl;
}
int main()
{
int f[4];
int i,j,m,n;
int a,b,c;
int d1,d2,d3;
Dian dian;
int temp1,temp2;
int flag=1;
while(flag){
dian.menu();
int k;
cin>>k;
if(k==1){
cout<<"请输入四个数字(两者之间用" "分离)"<<endl;
for(i=0;i<4;i++)
{
cin>>temp1;
if(temp1>13){
temp2=temp1%13;
cout<<"将 "<<temp1<<" 转化为 "<<temp2<<endl;
}
else temp2=temp1;
f[i]=temp2;
}
cout<<endl;
}
if(k==2){
for(i=0;i<4;i++)
{
f[i]=rand()%13;
cout<<f[i]<<" ";
}
cout<<endl;
}
for(i=0;i<4;i++)
for(j=0;j<4;j++)
if(j!=i)
for(m=0;m<4;m++)
if(m!=i&&m!=j)
for(n=0;n<4;n++)
if(n!=i&&n!=j&&n!=m)
for(a=1;a<5;a++)
for(b=1;b<5;b++)
for(c=1;c<5;c++)
{
d1=dian.judge(f[i],f[j],a);
d2=dian.judge(d1,f[m],b);
d3=dian.judge(d2,f[n],c);
if(d3==24)
{
cout<<f[i];
cout<<dian.print(a);
cout<<f[j];
cout<<dian.print(b);
cout<<f[m];
cout<<dian.print(c);
cout<<f[n]<<"=24"<<endl;
}
}
cout<<endl;
flag=dian.ceshi();
}
return 0;
}