由计算机“想”一个四位数,请人猜这个四位数是多少。人输入这个四位数后,计算机首先判断这四个数中有几个猜对了,并且在猜对的数字中又有几位位置也是对的,将结果显示出来,给人以提示,请人再猜,直到人猜出计算机所想的四位数为止。请编程实现该游戏,游戏结束时,显示人猜一个数用了几次。
提示:用库函数random()产生一个随机数。
如:
Int z;
z= random(9999);
仅供参考!谢谢!
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int myrand()
{
srand((unsigned)time(NULL));
int a = rand() % 9000 + 1000;
return a;
}
int *fun(int x, int y)
{
static int r[2];
int arrx[4] = {0};
int arry[4] = {0};
int n = 0, m = 0;
arrx[0] = x / 1000;
arrx[1] = x / 100 % 10;
arrx[2] = x % 100 / 10;
arrx[3] = x % 10;
if (y > 999 && y < 10000)
{
arry[0] = y / 1000;
arry[1] = y / 100 % 10;
arry[2] = y % 100 / 10;
arry[3] = y % 10;
}
else
return NULL;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
if (arrx[i] == arry[j])
{
n++;
if (i == j)
m++;
break;
}
}
}
r[0] = n;
r[1] = m;
return r;
}
int main(int argc, char *argv[])
{
int x = myrand();
int *p = NULL;
int y = 0;
int n = 0;
puts("输入一个四位数:");
do
{
scanf("%d", &y);
n++;
if (x == y)
{
puts("恭喜猜对了!");
printf("一共猜了%d次。\n", n);
break;
}
else
{
p = fun(x, y);
printf("猜对了%d个数\n", p[0]);
printf("有%d个位置且数字都是正确的\n", p[1]);
puts("\n请重新猜!:");
}
} while (y != x);
return 0;
}
#include <random>
#include <iostream>
#include <vector>
#include "algorithm" //sort函数、交并补函数
#include "iterator" //求交并补使用到的迭代器
#include <cmath>
using namespace std;
int main()
{
random_device rd; //如果可用的话,从一个随机数发生器上获得一个真正的随机数
mt19937 gen(rd()); //gen是一个使用rd()作种子初始化的标准梅森旋转算法的随机数发生器
uniform_int_distribution<> distrib(1000, 9999);
int rand_num = distrib(gen);//生成随机数
int num_sp = 0;//猜测次数
vector<int> rand; //随机数各位数组
vector<int> in_num;//输入数字各位数组
int p = rand_num;
for(int i = 1 ;i <= 4 ; i++)
{
int n;
n = p % 10;
p = p/10;
rand.push_back(n);
}
int num;//输入的数字
int num_loca=0;//有几位猜中了
int num_data=0;//有几个数字猜对了
while(1)
{
cout<<"猜一个4位数:";
cin >> num;
num_sp++;
for(int i = 1,p=num ;i <= 4 ; i++)
{
int n;
n = p % 10;
p = p/10;
in_num.push_back(n);
}
if(rand_num == num)//猜对了
{
cout<<"猜对了"<<endl;
cout<< "一共猜了" << num_sp <<"次"<<endl;
return 0;
}
else if(rand_num != num)//猜错了
{
for(int i = 0 ; i < 4 ; i++)
{
if(rand[i] == in_num[i])
{
num_loca++;
continue;
}
}
cout<<"一共有"<< num_loca <<"位置正确"<<endl;
num_loca = 0;
}
//判断有多少位数字正确
vector<int> v;
vector<int> copy_rand = rand;
sort(copy_rand.begin(),copy_rand.end());
sort(in_num.begin(),in_num.end());
set_intersection(copy_rand.begin(),copy_rand.end(),in_num.begin(),in_num.end(),back_inserter(v));//求交集
cout<<"一共有"<< v.size() <<"个数字正确"<<endl;
v.clear();
in_num.clear();
}
return 0;
}