1、游戏要求
电脑自动生成1~100的随机数
玩家猜数字时提供反馈,直到猜对
1.1 猜数字游戏程序运行
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
void menu()
{
printf("****************\n");
printf("***1.进入游戏****\n");
printf("***0.退出游戏****\n");
printf("****************\n");
}
void game()
{
int guss = 0;
int r = rand() % 100 + 1;
while (1)
{
printf("你猜的数字:>");
scanf("%d", &guss);
if (guss < r)
{
printf("猜小了\n");
}
else if (guss > r)
{
printf("猜大了\n");
}
else
{
printf("猜对了\n");
break;
}
}
}
int main()
{
int i = 0;
srand((unsigned int)time(NULL));
do
{
menu();
printf("是否进入游戏:>");
scanf("%d", &i);
switch (i)
{
case 1:
{
game();
break;
}
case 0:
{
printf("退出游戏:>");
break;
}
default:
{
printf("请重新猜数字:>\n");
break;
}
}
} while (i);
return 0;
}
1.2 程序优化
加入次数限制,增加游戏趣味性
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
void menu()
{
printf("***********************\n");
printf("***** 1. play ******\n");
printf("***** 0. exit ******\n");
printf("***********************\n");
}
void game()
{
int r = rand() % 100 + 1;
int guss = 0;
int count = 5;
while (count)//用count进行限制
{
printf("你还有%d次猜数字的机会\n", count);
printf("请猜数字:");
scanf("%d", &guss);
if (r < guss)
{
printf("猜大了\n");
}
else if (r > guss)
{
printf("猜小了\n");
}
else
{
printf("恭喜你,猜对了\n");
break;
}
count--;
}
if(count==0)
printf("猜数字失败,正确的值是:%d\n", r);
}
int main()
{
int i = 0;
srand((unsigned int)time(NULL));
do
{
menu();
printf("请选择:>");
scanf("%d", &i);
switch (i)
{
case 1:
{
game();
break;
}
case 0:
{
printf("退出游戏\n");
break;
}
default:
{
printf("选择错误,重新选择\n");
break;
}
}
} while (i);
return 0;
}
2、关联知识点
2.1 rand函数
rand可以生成随机数,返回伪随机数,需要包含头文件:stdlib.h
伪随机数是用确定性的算法计算出来自[0,1]均匀分布的随机数序列。并不真正的随机.在计算伪随机数时,若使用的初值(种子)不变,那么伪随机数的数序也不变
rand
函数生成随机数的默认种子是1
函数原型:
int rand (void)//函数不需要参数
2.2 srand函数
通过srand
函数的参数seed
来设置rand
函数生成随机数的种子,先调用srand函数
后调用rand函数
srand调用函数规定是unsigned int,
而time返回值类型是int,
所以要使用srand必须强制类型转换
原型:
void srand(unsigned int seed);//调用一次即可
2.3 time函数
需要包含头文件time.h
。一般使用程序运行时间
作为种子,原型:
time_t time (time_t* timer);//
time函数返回当前的日历时间(计算机起始时间到现在的运行时间的差值(时间戳)
),返回的类型是time_t
本质是一个适合存储日历时间的整型类型
time
函数的参数timer=NULL
时得到当前时间(从1970-01-01 00:00:00到现在的秒数)
timer=时间数值
时,用于设置时间,time_t是一个unsigned long类型。如果 timer非NULL,则返回的差值存储在变量 timer中。
只让time函数返回时间戳,可以写成:time(NULL)
(没有接收返回值)
2.4 生成随机数
#include<stdio.h>
#include<stdlib.h>
#include<time.h>//使用time函数的返回值设置种子
int main()
{
srand((unsigned int)time(NULL));//调用一次即可
printf("%d\n", rand());
printf("%d\n", rand());
printf("%d\n", rand());
printf("%d\n", rand());
printf("%d\n", rand());
return 0;
}
(每次打印的值都不同)
2.4.1 生成范围值随机数
2.4.1.1 生成0~99之间的随机数
rand()%100//余数的范围是0~99
2.4.1.2 生成1~100之间的随机数
rand()%100+1;
2.4.1.3 生成a~b的随机数
a+rand()%(b-a+1);