小游戏——猜数字

猜数字游戏:

详细规则请看:猜数字_百度百科

这个游戏很简单,也就是两个函数就可以解决了。

首先,需要判断两个数各位数字是否有相同或者是否在同一位置上,这样给出一个judgedata(int A,int B)函数。

 1 void judgedata(int A, int B)
 2 {
 3     int count1=0;
 4     int count2=0;
 5     int a[4],b[4];
 6     for(int k=3; k>=0; k--)
 7     {
 8         a[k]=A%10;
 9         b[k]=B%10;
10         //cout<<a[k]<<" "<<b[k]<<endl;
11         A/=10;
12         B/=10;
13     }
14     for(int i=0; i<4; i++)
15     {
16         for(int j=0; j<4; j++)
17         {
18             if((a[i]==b[j])&&(i==j))    
19                 count1++;
20                 
21         else
22             if((a[i]==b[j])&&(i!=j))    
23                 count2++;    
24         }
25     }
26     if(count1==4&&count2==0)
27     {
28        cout<<"\t你成功了!"<<endl; 
29        cout<<"\t"<<count1<<"A"<<count2<<"B"<<endl;
30     }
31     else
32        cout<<"\t"<<count1<<"A"<<count2<<"B"<<endl;
33 }

然后接着一个随机数生成器

 1 int random1() 
 2 {  
 3         
 4       int a[10],b,c[4]; 
 5       for(int i=0;i<10; i++) 
 6       { 
 7           a[i]=i; 
 8       } 
 9       for(int j=1; j<5; j++) 
10       { 
11             
12           b=rand()%9+1;  
13           c[j]=a[b]; 
14       } 
15       return c[1]*1000+c[2]*100+c[3]*10+c[4]; 
16 }

最后整个程序就是:

#include<iostream>
 #include<vector>
 using namespace std;
 
 //随机数生成器
 int random1()
 { 
       
       int a[10],b,c[4];
       for(int i=0;i<10; i++)
       {
           a[i]=i;
       }
       for(int j=1; j<5; j++)
       {
           
           b=rand()%9+1; 
           c[j]=a[b];
       }
       return c[1]*1000+c[2]*100+c[3]*10+c[4];
 }
 
        
 void judgedata(int A, int B)
 {
     int count1=0;
     int count2=0;
     int a[4],b[4];
     for(int k=3; k>=0; k--)
     {
         a[k]=A%10;
         b[k]=B%10;
         //cout<<a[k]<<" "<<b[k]<<endl;
         A/=10;
         B/=10;
     }
     for(int i=0; i<4; i++)
     {
         for(int j=0; j<4; j++)
         {
             if((a[i]==b[j])&&(i==j))    
                 count1++;
                 
         else
             if((a[i]==b[j])&&(i!=j))    
                 count2++;    
         }
     }
     if(count1==4&&count2==0)
     {
        cout<<"\t你成功了!"<<endl; 
        cout<<"\t"<<count1<<"A"<<count2<<"B"<<endl;
     }
     else
        cout<<"\t"<<count1<<"A"<<count2<<"B"<<endl;
 }
 
 
 int main()
 {
     
     int A,B;
     A=random1();
     //cout<<A<<endl;
     int i=1;
     cout<<"\t......................................................"<<endl<<endl;
     cout<<"\t\t\t\t"<<"猜数字"<<endl<<endl;
     cout<<"\t......................................................"<<endl<<endl;
 
     cout<<"\t请输入一个不重复的四位数(你有八次的机会):"<<endl;
 
     while(i<9)
     {
             cout<<"\t第"<<i<<"次输入:"<<endl; 
             cout<<"\t";cin>>B;
             judgedata(A, B);
             cout<<"\t你还有"<<8-i<<"次机会!"<<endl;
     }
     return 0;
 }

 

 

posted on 2012-08-18 17:06  kaka_  阅读(268)  评论(0编辑  收藏  举报

导航