C语言程序题
用户从键盘输入4位不重复的数,来匹配计算机给出的4位随机数,若数字和位置均等同,表示用户赢了。每猜一次,计算机均给出提示信息(x,y),x表示数字、位置都匹配的个数;y表示数字匹配但位置不匹配的个数。这个题目有高手会编吗?
程序代码:#include <stdio.h>
#include <math.h>
int rand();
void fun1(int n)
{
int a,b,c,d;
int a1,b1,c1,d1;
int x,y;
int num;
//printf("n=%d\n",n);
a=n%1000;
b=n%100/10;
c=n%10/100;
d=n/1000;
while(1)
{
printf("输入你的数字:\n");
scanf("%d",&num);
a1=num%1000;
b1=num%100/10;
c1=num%10/100;
d1=num/1000;
x=y=0;
if(a==a1)
x++;
else
y++;
if(b==b1)
x++;
else
y++;
if(c==c1)
x++;
else
y++;
if(d==d1)
x++;
else
y++;
printf("相同x=%d,不相同y=%d\n",x,y);
if(x==4)
{
printf("恭喜你猜对!");
printf("你猜到的书是:%d\n",num);
break;
}
}
}
void fun()
{
int n;
int a,b,c,d;
int flag=1;
while(flag)
{
while((n=rand()%10000)<1000);
a=n%1000;
b=n%100/10;
c=n%10/100;
d=n/1000;
if(a!=b&&a!=c&&a!=d&&b!=c&&b!=d&&c!=d)
{
fun1(n);
flag=0;
}
}
}
int main()
{
fun();
return 0;
}
程序代码:#include<iostream>
#include<map>
#include<cstdlib>// just for rand
using namespace std;
class Guess{
private:
map<char,int> theMap;
char buf[4];
protected:
bool evalue()
{
int x,y;
x=y=0;
for( int i =0 ; i<4;i++)
{
map<char,int>::iterator iter=theMap.find(buf[i]);
if( iter->second== i )
x++;
else if ( iter != theMap.end())
y++;
}
cout<<"( "<<x<<", "<<y<<" )"<<endl;
if ( x== 4)
return true;
return false;
}
public:
Guess(){
for( int i=0;i<4;i++)
{
theMap.insert(make_pair((char)(rand()%10+'0'),i));
}
}
void function()
{
while(1){
cin>>buf;
if ( true == evalue())
break;
}
}
};
int main()
{
Guess guess;
guess.function();
return 0;
}