猜数字

来源:互联网 发布:网络诊断114是什么意思 编辑:程序博客网 时间:2024/06/03 00:20

/*=================猜数字=====================
输入四个不重复的数字用空格隔开,按Enter后输出结果,形式为“?A?B”
四个数字中位置和数字都正确为A,数字相同而位置不同为B,当4A时为
猜对,你只有八次机会!*/
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;

int A=0,B=0;
int a[4];

bool Test(int aa,int bb,int cc,int dd){
 if(((aa<0 || aa>9) || (bb<0 || bb>9) || (cc<0 || cc>9) || (dd<0 || dd>9))
  || (aa==bb) || (aa==cc) || (aa==dd) || (bb==cc) || (bb==dd)

|| (cc==dd)) return false;
 else return true;
}

void answer(){
 int i;
 srand((unsigned) time (NULL) );
 do{
  for(i=0;i<=3;i++) a[i] = rand()%10;
 }while(!Test(a[0],a[1],a[2],a[3]));
}


void judge(int w,int x,int y,int z);
void get(){

 int aa,bb,cc,dd;

 
 do{
  cout << "enter 4 different number:";
  cin >> aa >> bb >> cc >> dd;
 }while(!Test(aa,bb,cc,dd));
 judge(aa,bb,cc,dd);
}

void judge(int w,int x,int y,int z){

 int b[]={w,x,y,z};
 int i,k;

 for(i=0;i<=3;i++){
  k=i-1;
  for(int j=0 ; j<=3 ; j++){
   if(a[i]==b[k++%4+1]){
    if(i==k) A++;
    else B++;
   }
  }
 }
 if(A == 4){
  cout << "right!!" << endl;
  //我想在这里跳到主函数开始处
 } 
 cout << A <<"A" << B << "B" << endl;
 //cout << "The correct answer is: "<<a[0] <<" "<<a[1] <<" "<<a[2] <<" "<<a[3] <<endl;
 A = 0;B = 0;
}

int main()
{
 cout << "====================猜数字=================="<<endl<<
 "输入四个不重复的数字用空格隔开,按Enter后输出结果,形式为?A?B"<<endl
 <<"四个数字中位置和数字都正确为A,数字相同而位置不同为B,当4A时为"<<endl
 <<"猜对,你只有八次机会!"<<endl;
 cout << "/n☆☆☆Start a new game!☆☆☆/n";
 while(1){
  answer();
  for(int n=1;n<=8;n++){
   get();
  }
 cout << "The correct answer is: "<<a[0] <<" "<<a[1] <<" "<<a[2] <<" "<<a[3] <<endl;
 }
 return 0;
}