要求:
1. 电脑⾃动⽣成1~100的随机数
2. 玩家猜数字,根据猜测数据的⼤⼩给出⼤了或⼩了的反馈,直到猜对,游戏结束
生成随机数
rand函数
rand函数⽣成的随机数是伪随机的,是通过某种算法⽣成的随机数。
真正的随机数的是⽆法预测下⼀个值是多少的。⽽rand函数是对⼀个叫“种⼦”的基准值进⾏运算⽣成的随机数。 之所以每次运⾏程序产⽣的随机数序列是⼀样的,是因为rand函数⽣成随机数的默认种⼦是1。 如果要⽣成不同的随机数,就要让种⼦是变化的。
#include <stdio.h>
#include <stdlib.h>//rand函数的使⽤需要包含的头⽂件
int main()
{
printf("%d\n", rand());//41
printf("%d\n", rand());//18467
printf("%d\n", rand());//6334
return 0;//每次生成的随机值都是上面三个
}
srand函数
程序中在调⽤rand函数之前先调⽤srand函数,通过srand函数的参数seed来设置rand函数⽣成随 机数的时候的种⼦,只要种⼦在变化,每次⽣成的随机数序列也会变化。给srand的种⼦是如果是随机的,rand就能⽣成随机数。
time函数
time 函数是1970年1⽉1⽇0时0分0秒到现在时间之间的差值,单位是秒。返回的类型是time_t类型的,time_t类型本质上是32位或者64位的整型类型。
time函数的参数timer如果是⾮NULL的指针的话,函数也会将这个返回的差值放在timer指向的内存 中带回去。 如果timer是NULL,就只返回这个时间的差值。time函数返回的这个时间差叫时间戳。
time函数的时候需要包含头⽂件:time.h
//随机数的生成
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
//使⽤time函数的返回值设置种⼦
//因为srand的参数是unsigned int类型,我们将time函数的返回值强制类型转换
srand((unsigned int)time(NULL));
printf("%d\n", rand());
printf("%d\n", rand());
printf("%d\n", rand());
return 0;
}
限定1-100
rand()%100+1;//%100的余数是0~99,0~99的数字+1,范围是1~100
生成a-b的随机数的方法:a + rand()%(b-a+1)
参考代码:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void game()
{
int r = rand() % 100 + 1;
int guess = 0;
int count = 5;
while (count)
{
printf("\n你还有%d次机会\n", count);
printf("请猜数字>:");
scanf("%d", &guess);
if (guess < r)
{
printf("猜小了\n");
}
else if (guess > r)
{
printf("猜大了\n");
}
else
{
printf("恭喜你,猜对了\n");
break;
}
count--;
}
if (count == 0)
{
printf("你失败了,正确值是:%d\n", r);
}
}
void menu()
{
printf("***********************\n");
printf("****** 1. play ******\n");
printf("****** 0. exit ******\n");
printf("***********************\n");
}
int main()
{
int input = 0;
srand((unsigned int)time(NULL));
do
{
menu();
printf("请选择:>");
scanf("%d", &input);
switch (input)
{
case 1:
game();
break;
case 0:
printf("游戏结束\n");
break;
default:
printf("选择错误,重新选择\n");
break;
}
} while (input);
return 0;
}