1.整体思路
玩游戏的话最少要玩一次所以整体框架我们选择do while 循环,我们猜的数字一定是随机产生的数字,所以我们的代码中要实现随机数的产生。
2.如何产生随机数
利用rand函数产生随机数
注意:在调用rand 函数之前要首先使用srand 函数设置随机数生成起点
而使用srand 时一般要配合time函数来随机产生随机数具体用法如下
引入时间戳
// 设置生成10个随机数
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
void main( void )
{
int i;
//用时间戳设置随机数的生成,以便于我们每一次都能得到不一样的随机数
srand( (unsigned)time( NULL ) );
for( i = 0; i < 10;i++ )
printf( " %6d\n", rand() );
}
3.代码实现
废话不多说,上代码!!!
#include <stdio.h>
#include<stdlib.h>
#include<time.h>
void menu()
{
printf("***************\n");
printf("***************\n");
printf("*** 1.Start ***\n");
printf("*** 2.Exit ***\n");
printf("***************\n");
printf("***************\n");
}
void game()
{
int ret = 0;
int random_n = rand() % 100 + 1;
while (1)
{
printf("请输入数字-->\n");
scanf("%d", &ret);
if (ret > random_n)
{
printf("猜大了");
}
if ( ret < random_n )
{
printf("猜小了");
}
if (ret == random_n)
{
printf("恭喜你,猜对了");
break;
}
}
}
int main( )
{
srand((unsigned)time(NULL));
menu( );
int n = 0;
do
{
scanf("%d", &n);
switch (n)
{
case 1:
game();
break;
case 0:
printf("退出游戏");
break;
default:
printf("输入错误,请重新输入");
break;
}
} while (n);
return 0;
}