C语言-随机数rand

rand(),产生一个随机数,要和srand()连用
#include <stdlib.h> //rand(),srand()头文件
#include <time.h> //time()头文件

	#include <stdlib.h>//rand()头文件
	#include <time.h>//srand()头文件
	int main(void)
	{
		//随机种子
		srand((unsigned int)time(NULL));//time(NULL)得到当前系统时间
		int i = 0;
		while (i < 20)
		{
			//产生随机数
			int n = rand();
			n = 50 + n % 71;//产生50~120的随机数
	
			printf("%d\n", n);
			i++;
		}
	}

分析要产生50~120的随机数
rand()%10 随机数为:0~9
rand()%51 随机数为:0~50
70 + rand()%51 随机数为:70~120

测试结果为:
在这里插入图片描述

//随机产生指定数组中的元素

	//随机种子
	srand((unsigned int)time(NULL));//time(NULL)得到当前系统时间
	//随机产生指定数组中的元素
	int num[10] = { 2, 324, 923, 89, 34, 80, 23, 74, 293, 19 };
	
	int i = 0;
	while (i < 20)
	{
		//产生随机数
		int n = rand();
		n = n % 10;//产生50~120的随机数

		printf("%d\n", num[n]);
		i++;
	}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43340991/article/details/86564836