C语言之随机数生成超详解

1.首先来看一段简单的代码

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

int main(void)
{
	int i;
        printf(" %6d\n", rand());

	system("pause");
}

运行这个程序你会发现,每次重启程序。

生成的随机数都是固定的,这样怎么还能叫随机数呢




2.解决方法>srand()

srand()就是给rand()提供一个种子

srand(time);//这样子可以打印出来符合要求的随机数,但是我们要使用下面的形式

为了time类型和srand类型统一,使用强制类型转换(unsigned):

srand((unsigned) time(NULL));

3.满足需求的随机数

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

int main(void)
{
	int i;
	srand((unsigned)time(NULL));

	for (i = 0; i < 10; i++)
	{
		printf(" %6d\n", rand());
	}
	system("pause");
}




猜你喜欢

转载自blog.csdn.net/csdn_kou/article/details/79788815
今日推荐