C语言编程练习,猜数字游戏实现
编程记录,关于B站上鹏哥C语言课程中的练习记录 记录内容:C语言实现猜数字游戏(关于do-while循环)
第一步,关于猜数字游戏整体框架
-
1.menu()函数打印菜单进行动作指示。 2.game()函数内容为主要的判断数字正确与否的内容。 3.main()函数即运行过程。
第二步,具体内容
-
关于菜单打印 菜单可以循环出现,涉及循环语句do-while,直到用户输入0时程序完全结束。 循环开始首先打印菜单。 涉及条件语句,采用switch语句,输入1,进入game()开始游戏;输入0,退出循环;输入其他数字,显示输入错误要求重新输入,并且清空当前页面。 关于游戏内容 首先是关于随机数的生成,通过随机数来进行猜数游戏 使用rand函数生成随机数,并且将随机数介于1-100之间 仅使用rand函数每次随机数相同,要再加入srand一起使用,且加上 stdlib.h头文件
Example
/* RAND.C: This program seeds the random-number generator
* with the time, then displays 10 random integers.
*/
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
void main( void )
{
int i;
/* Seed the random-number generator with current time so that
* the numbers will be different every time we run.
*/
srand( (unsigned)time( NULL ) );
/* Display 10 numbers. */
for( i = 0; i < 10;i++ )
printf( " %6d
", rand() );
}
其中,需要为srand提供一个变换的参数才能生成随机数,time()作为时间戳提供参数,但time()本身返回值是int类型,而srand需要unsigned int类型,所以进行强制类型转换。 每次工程开始只需要进行一次初始值设置,所以srand语句不在循环内部。
随机数生成完成后,用户每次输入数字进行比较,并给出相应提示,最后得出正确结果即可。
最终代码如下
#include<stdio.h>
#include<windows.h>
#include <time.h>
#include<stdlib.h>
void menu()
{
printf("********************
");
printf("****** 1 play ******
");
printf("****** 0 exit ******
");
printf("********************
");
}
void game()
{
int random_num = rand() % 100 + 1;
//printf("%d", random_num);
int input = 0;
while (1)
{
printf("请输入你所猜的数字:");
scanf("%d", &input);
if (input < random_num)
printf("你的数字太小了!
");
else if(input>random_num)
printf("你的数字太大了!
");
else
{
printf("恭喜猜对!
");
Sleep(2000);
system("cls"); //完成后保持显示一会然后清屏
break;
}
}
}
int main()
{
int input = 0;
srand((unsigned)time(NULL));
do
{
menu();
printf("输入操作要求(0/1):");
scanf("%d", &input);
switch (input)
{
case 1:
game();
break; //每一个case和default最好先都加上break
case 0:
break;
default:
printf("输入错误,请重新输入。
");
Sleep(500);
system("cls");
break;
}
}while (input); //input存在即input==1
return 0;
}
