在学习C语言课的时候老师讲到猜数字小游戏,根据老师讲的自己做了小小的改版,挺有意思的,这个小游戏的代码核心就是随机数的生成,rand()函数和srand()函数的使用以及使用时间戳来定义一个随机的起点来确保每一次数字都是随机的
#include "stdio.h"
#include "stdlib.h"
#include "time.h"
int judge_num = 0 ;
void game()
{
int guess = 0;
//generate radom number
int ret = rand()%100+1;
///Determine whether the number are correct
while (1)
{
printf("please enter what number your want->");
scanf("%d",&guess);
if(guess < ret)
{
printf("guess small,please guess again\n");
continue;
}
else if(guess > ret)
{
printf("guess large ,please guess again\n");
continue;
}
else
{
printf("congartulation guess right ");
printf("Do you want paly again \n 1.yes\n 2.no\n ->");
scanf("%d",&judge_num);
break;
}
}
}
void menu()
{
printf("*******************\n");
printf("*******1.paly******\n");
printf("*******2.exit******\n");
printf("*******************\n");
scanf("%d",&judge_num);
while (judge_num == 1)
{
game();
}
if (judge_num == 2)
{
printf("exit game");
}
}
int main()
{
srand((unsigned int)time(NULL));
//creat entry menu
menu();
}