本帖最后由 smilencetion 于 2022-12-20 15:08 编辑
说到猜数字,以前看别人发的题也写了一个,还挺好玩的,位数长了以后要好好推理才行
[C] 纯文本查看 复制代码 猜数字
1.输入要猜的数字的位数n(n<=10)
2.计算机随机生成一个n位数(各位数字相异)
3.输入猜测的数字 给出提示信息如:A1B2
A表示位置和数字均正确的个数,B表示位置不正确但是数字正确的个数
4.根据提示信息继续猜数字
1次内猜对 给出天才提示
8次内猜对 给出大神提示
16次内猜对 给出有潜力提示
16次仍没有猜对 给出需努力提示
[C] 纯文本查看 复制代码 #include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define CNT 16
long long getnum(int);
long long guessnum(int, long long);
int has(long long, int);
int count = 0;
int a[10];
int main(void)
{
int n, A, B, t;
long long num, guess;
do
{
printf("请输入位数n(1<=n<=10):");
t = scanf("%d", &n);
while (getchar() != '\n')
continue;
} while (t != 1 || n < 1 || n > 10);
putchar('\n');
num = getnum(n);
guess = guessnum(n, num);
while (count < CNT)
{
A = B = 0;
long long tmpN = num;
long long tmpG = guess;
while (tmpN)
{
A += tmpN % 10 == tmpG % 10;
B += has(num, tmpG % 10) && (tmpN % 10 != tmpG % 10);
tmpN /= 10;
tmpG /= 10;
}
printf("猜测结果:A%dB%d\n\n", A, B);
if (A < n && count < CNT)
{
guess = guessnum(n, num);
continue;
}
else
break;
}
if (count == CNT && A < n)
puts("还需努力");
else if (count > 8)
puts("有潜力");
else if (count > 1)
puts("大神");
else if (count == 1)
puts("天才");
return 0;
}
long long getnum(int n)
{
long long num = 0;
srand((unsigned)time(NULL));
for (int i = 0, t; i < n; i++)
{
do
{
t = rand() % 10;
} while ((i == 0 && t == 0 && n > 1) || a[t] == 1);
a[t] = 1;
num = 10 * num + t;
}
return num;
}
long long guessnum(int n, long long num)
{
long long guess;
int t;
do
{
count++;
printf("第%d次猜测,请输入你的猜测(%d位数):", count, n);
t = scanf("%I64d", &guess);
while (getchar() != '\n')
continue;
} while ((int)log10(guess) != (int)log10(num) || t != 1);
return guess;
}
int has(long long a, int b)
{
while (a)
{
if (a % 10 == b)
return 1;
a /= 10;
}
return 0;
} |