比特鹏哥4-随机数的生成【自用笔记】

随机数的生成

1.Rand

语句结构
# include <stdlib.h>   //头文件
int rand(void)

注:rand生成的随机数是伪随机数,rand对应的“种子”的基准值都是1

2. srand

语句结构
void  srand(unsigned  int seed)

注:此时的seed是可以变化的, 那么随之对应的随机数序列也就发生变化。

3.time

语句结构

在程序中我们一般是使用程序运行的时间作为种子的,
在C语言中有一个函数叫 time ,就可以获得这个时间。

#include<time.h>//头文件
 time_t  time (time_t*  timer);

time 函数会返回当前的日历时间,
返回的是1970年1月1日0时0分0秒到现在程序运行时间之间的差值,单位是秒。

返回的类型是time_t类型的,
time_t类型本质上其实就是32位或者64位的整型类型。

4.设置随机数的范围

设置0~99之间的随机数
rand()%100
设置1~100之间的随机数
rand()%100+1;//%100的余数是0~99,0~99的数字+1,范围是1~100
设置100~200之间的随机数
 100 + rand()%(200-100+1)
设置a~b之间的随机数
a+ rand()%(b-a+1)

实际问题:猜数字游戏实现

1.生成1~100内的随机数
#include<stdlib.h>
#include <time.h>


srand((unsigned int)time(NULL));
int r= rand() % 100 + 1;
2.猜数字



#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include<stdlib.h>
#include <time.h>



void  meau() 
{
	printf("**************************n");
	printf("***********1.play*********n");
	printf("***********0.exit*********n");
	printf("**************************n");
}
void game() {
	//1.生成随机数
	
	int r= rand() % 100 + 1;
	//2.猜数字
	int guess = 0;
	while (1) {

	printf("请猜数字:");
	if (guess > r)
		printf("猜大了!");
	else if (guess < r)
		printf("猜小了!");
	else
		printf("恭喜你,猜对了!");
	break;
	}
	}
int main() {

	int input = 0;
	srand((unsigned int)time(NULL));//随机数字只调用一次
	do
	{//打印菜单
		meau();
		pritnf("请选择:>");
		scanf("%d", &input);
		switch (input) {
			case 1:	
				game();
				printf("猜数字游戏n");
				break;
		 	case 0:  
				printf("退出游戏n");
				break;
			default:
				printf("选择错误,重新选择n");
				break;

		}
	} while (input);

	return 0;



}



本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>