c语言小游戏:猜数字 随机一个1-100之间的数,根据数据输入进行提示

c语言小游戏:猜数字 随机一个1-100之间的数,根据数据输入进行提示,第1张

//小游戏:猜数字 随机一个1-100之间的数,根据数据输入进行提示

#include <stdlib.h>

#include <time.h>

int main(void){

int value=0

int num=0

srand((unsigned int) time(NULL))

num=rand()%100+1//1-100

while(1){

scanf("%d",&value)

if(num>value){

printf("您猜小了\n")

}

else if(num<value){

printf("您猜大了\n")

}

else if(num=value){

printf("恭喜您猜对了\n")

break

}

}

return 0

}

源码如下:

/* 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

}

==============================================

运行结果见附图,希望我的回答能够对你有所帮助。


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/yw/7766331.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-04-09
下一篇2023-04-09

发表评论

登录后才能评论

评论列表(0条)

    保存