原创,代码:
#include<iostream>
#include<algorithm>
#include<cstdlib>
#include<ctime>
#include<windows.h>
#include<string>
using namespace std;
int a[4],o[3];
bool f;
string s,ans;
void clr() {
system("cls");
}
bool v(int c) {
return c=='+'||c=='-'||c=='*'||c=='/';
}
double cal(double x,double y,int op) {
switch(op) {
case'+':
return x+y;
case'-':
return x-y;
case'*':
return x*y;
case'/':
return y?x/y:-1e9;
}
return 0;
}
double cal(double x,double y,int op,string &s1,string &s2,string &res) {
res="("+s1+char(op)+s2+")";
switch(op) {
case'+':
return x+y;
case'-':
return x-y;
case'*':
return x*y;
case'/':
return y?x/y:-1e9;
}
return 0;
}
void findans() {
int p[4]= {0,1,2,3},op1,op2,op3;
string s1,s2,s3,s4,t1,t2,t3,r;
double v1,v2,v3;
do {
for(op1='+'; op1<='/'&&!ans.size(); op1+=13) {
for(op2='+'; op2<='/'&&!ans.size(); op2+=13) {
for(op3='+'; op3<='/'&&!ans.size(); op3+=13) {
s1=to_string(a[p[0]]);
s2=to_string(a[p[1]]);
s3=to_string(a[p[2]]);
s4=to_string(a[p[3]]);
v1=cal(a[p[0]],a[p[1]],op1,t1,t2,t1);
v2=cal(v1,a[p[2]],op2,t1,s3,t2);
v3=cal(v2,a[p[3]],op3,t2,s4,t3);
if(v3>23.999&&v3<24.001)ans=t1+"="+to_string((int)v1)+","+t2+"="+to_string((int)v2)+","+t3+"=24";
if(ans.size())return;
v1=cal(a[p[0]],a[p[1]],op1,t1,t2,t1);
v2=cal(a[p[2]],a[p[3]],op3,s3,s4,t2);
v3=cal(v1,v2,op2,t1,t2,t3);
if(v3>23.999&&v3<24.001)ans=t1+"="+to_string((int)v1)+","+t2+"="+to_string((int)v2)+","+t3+"=24";
if(ans.size())return;
}
}
}
} while(next_permutation(p,p+4)&&!ans.size());
}
void gen() {
do {
ans="";
for(int i=0; i<4; i++)a[i]=rand()%9+1;
findans();
} while(ans.empty());
}
void chk(int n,int m,int p,int q,int o1,int o2,int o3) {
string s1=to_string(a[n]),s2=to_string(a[m]),s3=to_string(a[p]),s4=to_string(a[q]);
string t1,t2,t3,r;
double v1,v2,v3;
v1=cal(a[n],a[m],o1,t1,t2,t1);
v2=cal(v1,a[p],o2,t1,s3,t2);
v3=cal(v2,a[q],o3,t2,s4,t3);
if(v3>23.999&&v3<24.001) {
f=1;
s=t1+"="+to_string((int)v1)+","+t2+"="+to_string((int)v2)+","+t3+"=24";
return;
}
v1=cal(a[n],a[m],o1,t1,t2,t1);
v2=cal(a[p],a[q],o3,s3,s4,t2);
v3=cal(v1,v2,o2,t1,t2,t3);
if(v3>23.999&&v3<24.001) {
f=1;
s=t1+"="+to_string((int)v1)+","+t2+"="+to_string((int)v2)+","+t3+"=24";
return;
}
}
void d() {
int p[4]= {0,1,2,3};
do {
chk(p[0],p[1],p[2],p[3],o[0],o[1],o[2]);
if(f)return;
chk(p[0],p[2],p[1],p[3],o[1],o[0],o[2]);
if(f)return;
chk(p[0],p[1],p[3],p[2],o[0],o[2],o[1]);
if(f)return;
} while(next_permutation(p,p+4));
}
int main() {
srand(time(0));
char r,c;
do {
clr();
f=0;
s="";
gen();
cout<<"数字:"<<a[0]<<","<<a[1]<<","<<a[2]<<","<<a[3]<<endl;
cout<<"输入3个运算符(+-*/),或输入?查看答案:";
cin>>c;
if(c=='?') {
cout<<"答案:"<<ans<<endl;
goto e;
} else {
char c2,c3;
cin>>c2>>c3;
if(!v(c)||!v(c2)||!v(c3)) {
cout<<"运算符不合法!"<<endl;
goto e;
}
o[0]=c;
o[1]=c2;
o[2]=c3;
d();
if(f) {
cout<<"成功组成24点!"<<endl;
cout<<"运算流程:"<<s<<endl;
} else {
cout<<"不正确!正确答案:"<<ans<<endl;
}
}
e:
cout<<"继续游戏?(y/n):";
cin>>r;
} while(r=='y'||r=='Y');
clr();
cout<<"欢迎下次光临!"<<endl;
return 0;
}