猜数字游戏的提示(C语言,来自于UVa340)
实现一个经典的“猜数字游戏”。给定游戏序列和用户猜的序列,统计有多少数字位置正确(A),有多少数字在两个序列都出现过但位置不对(B)。
此题强调正常的猜测序列不会有0,因此可以作为循环的跳出条件。
#include<stdio.h>
#define maxn 1010//宏定义
int main()
{
int i,j;
int n, a[maxn], b[maxn];//分别存储答案序列和猜测序列
int rnd = 0;//游戏轮数计数器
while (scanf("%d", &n) == 1 && n)//n=0是判断条件为0,自动跳出循环
{
printf("Game %d:\n", ++rnd);
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);//输入答案序列
while (true)//猜测序列有多条需要一个循环来实现
{
int A, B;
A = B = 0;
for ( i = 0; i < n; i++)
{
scanf("%d", &b[i]);
if (b[i] == a[i])//位置相同,数相同
A++;
}
if (b[0] == 0)break;//设置跳出条件
for ( i = 1; i <= 9; i++)//统计相应数字出现次数
{
int c1 = 0, c2 = 0;
for ( j = 0; j < n; j++)
{
if (a[j] == i) c1++;
if (b[j] == i) c2++;
}
B += c1 <= c2 ? c1 : c2;
}
printf(" (%d,%d)\n", A, B - A);
}
}
return 0;
}