求设计一个程序,24点游戏 游戏规则:从键盘输入任意1-13的4个数,然后用算术运算符“+、-、*

求设计一个程序,24点游戏 游戏规则:从键盘输入任意1-13的4个数,然后用算术运算符“+、-、*,第1张

#include <stdio.h>

#include <math.h>

double num[4]//存储4个数旁饥字

double pre = 1E-6//精度

int go(int n)

{

int i,j

if(n==1)

{

if(fabs(num[0]-24)<1E-6)

return 1

else

return 0

}

else

{

for(i=0i<n-1i++)

{

double a=num[i]

double b=num[i+1]

for(j=i+1j<n-1j++)

{

num[j]=num[j+1]

}

num[i]=a+b

if(go(n-1)) return 1

num[i]=a-b

if(go(n-1)) return 1

num[i]=a*b

if(go(n-1)) return 1

if(b!=0)

{

num[i]=a/b

if(go(n-1)) return 1

}

for(j=n-1j>i+1j--)

{

num[j]=num[j-1]

}

num[i+1]=b

num[i]=a

}

}

return 0

}

int main()

{

double sum

int i

do

{

sum=0

for(i=0i<4i++)

{

scanf("辩启隐%lf",&num[i])

sum+=num[i]

}

if(sum>1)

{

if(go(4))

printf("YES\携厅n")

else

printf("NO\n")

}

}while(sum>1)

return 0

}

#include<iostream>

#include<math.h>

using namespace std

const double MIN=1E-6

void Print(int *Rank,double *FourNum)

{

for(int i=0i<4i++)

cout<<FourNum[Rank[i]]<<" "

cout<<endl

}

void Calculate_24(int *Rank,int *FourNum,char *Oper,int i,int j,int k,bool def)

{

double res=0

switch(i)

{

case 0:

res=FourNum[Rank[0]]+FourNum[Rank[1]]

break

case 1:

res=FourNum[Rank[0]]-FourNum[Rank[1]]

break

case 2:

res=FourNum[Rank[0]]*FourNum[Rank[1]]

break

case 3:

res=FourNum[Rank[0]]/FourNum[Rank[1]]

break

}

switch(j)

{

case 0:

res=res+FourNum[Rank[2]]

break

case 1:

res=res-FourNum[Rank[2]]

break

case 2:

res=res*FourNum[Rank[2]]

break

case 3:

res=res/FourNum[Rank[2]]

break

}

switch(k)

{

case 0:

res=res+FourNum[Rank[3]]

break

case 1:

res=res-FourNum[Rank[3]]

break

case 2:

res=res*FourNum[Rank[3]]

break

case 3:

res=res/FourNum[Rank[3]]

break

}

if(fabs(res-24)>MIN)

return

else

{

def=true

for(int num=1num<=7num++)

{

switch(num)

{

case 1:

cout<<FourNum[Rank[0]]

break

case 3:

cout<<FourNum[Rank[1]]

break

case 5:

cout<<FourNum[Rank[2]]

break

case 7:

cout<<FourNum[Rank[3]]

break

case 2:

cout<<Oper[i]

break

case 4:

cout<<Oper[j]

break

case 6:

cout<<Oper[k]

break

}

}

cout<<endl

}

}

void SearchTree(int Depth,int *Rank,int *FourNum,char *Oper,bool def)

{

int i,j,k

if(Depth==4)

{

for(i=0i<4i++)

for(j=0j<4j++)

for(k=0k<4k++)

Calculate_24(Rank,FourNum,Oper,i,j,k,def)

}

else

{

for(i=0i<4i++)

{

int Remember=0

for(j=0j<答答Depthj++)

{

if(Rank[j]==i)

Remember=1

}

if(Remember)

continue

Rank[Depth]=i

SearchTree(Depth+1,Rank,FourNum,Oper,def)

}

}

}

int main()

{

int a[4],b[4],time

char c[4]={'+','-','*','/'}

bool def=false

cin>>time

while(time--)

{

for(int i=0i<4i++)//御举虚输入测试数据

cin>>a[i]

cout<<"所镇燃有可能的结果:"<<endl

SearchTree(0,b,a,c,def)

if(def==false)

cout<<"No"<<endl

}

return 0

}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/12382738.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-25
下一篇 2023-05-25

发表评论

登录后才能评论

评论列表(0条)

保存