2025-02-25 03:04:11
源码如下:
/* File: guess.c */
#include <stdio.h> /* standard input & output support */
#include <stdlib.h> /* srand() rand() */
#include <time.h> /* time() */
/* 宏定义 */
#define NUMBER_LENGTH 5 /* 随机数长度 */
#define NUMBER_LIMIT 10 /* 随机数限制, 每一位0-9 */
#define INPUT_LENTH 128 /* 输入缓冲区大小 */
char goal[NUMBER_LENGTH] = {0}; /* 保存随机数 */
char flag[NUMBER_LIMIT] = {0}; /* 保存随机数标志, 保证不重复 */
char input[INPUT_LENTH] = {0}; /* 保存输入 */
/* 初始化用于保存数据的数组 */
void initData()
{
int i = 0;
while (i < NUMBER_LENGTH)
goal[i++] = 0;
i = 0;
while (i < NUMBER_LIMIT)
{
flag[i++] = 0;
}
}
/* 初始化用于保存缓冲区的数组 */
void initBuffer()
{
int i = 0;
while (i < INPUT_LENTH)
input[i++] = 0;
}
/* 显示猜测结果 */
void display()
{
int count = 0;
int i = 0;
while (i < NUMBER_LENGTH)
{
if (input[i] == goal[i])
{
printf("%c", 'o');
count++;
}
else
{
printf("%c", 'x');
}
i++;
}
printf("\nRIGHT: %d bit(s)\n", count);
if (count == NUMBER_LENGTH)
{
printf("You win! The number is %s.\n", goal);
exit(0);
}
}
/* 生成随机数 */
void general()
{
/* 以时间作为时间种子保证生成的随机数真正具有随机性质 */
srand((unsigned int)time(NULL));
int i = 0;
while (i < NUMBER_LENGTH)
{
char tmp;
do
{
tmp = '0' + ((i != 0) ? (rand() % 10) : (1 + rand() % 9));
} while (flag[tmp] != 0);
flag[tmp] = 1;
goal[i++] = tmp;
}
}
/* 输入方法,用于猜测 */
void guess()
{
printf("Please input the number you guessed:\n");
scanf("%s", input);
display();
initBuffer();
}
/* 主函数,程序主框架 */
int main (int argc, const char * argv[])
{
initData();
initBuffer();
general();
while (1) guess();
return 0;
}
==============================================
运行结果见附图,希望我的回答能够对你有所帮助。
2025-02-25 00:23:33
2025-02-25 01:45:10