rand和srand的用法

rand和srand

在man手册里面有讲述到,rand,rand_r和srand 都是与这个pseudo-random number generator有关的
伪随机数字发生器,就是产生随机数的lor

SYNOPSIS
#include <stdlib.h>
int rand(void);
int rand_r(unsigned int *seedp);
void srand(unsigned int seed);

原型是上面那样描述的。

DESCRIPTION
The rand() function returns a pseudo-random integer in the range 0 to
RAND_MAX inclusive (i.e., the mathematical range [0, RAND_MAX]).
The srand() function sets its argument as the seed for a new sequence
of pseudo-random integers to be returned by rand(). These sequences
are repeatable by calling srand() with the same seed value.
If no seed value is provided, the rand() function is automatically
seeded with a value of 1.

描述里面说rand的返回值是一个0到RAND_MAX的数,给rand设置一个seed的话就默认seed为1。
如果每个seed都一样的话呢,那每一次产生的随机数也一样了。
所以要用srand来产生一个seed,然后rand用这个seed来产生随机数。

代码

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

int main(int argc,char *argv[])
{
	if(2 != argc)
	{
		printf("usage: ./a.out num\n");
		return -1;
	}
	
	printf("randmax = %d\n",RAND_MAX);
	int aa = atoi(argv[1]);
	int c = 0;
	time_t tloc;
	time(&tloc);
	printf("tloc = %ld\n",tloc);
	srand(tloc);
	int i =0;
	for(i=0;i<aa;i++)
		{
			c = (rand() % 10);
			printf("c = %d\n",c);
		}

	return 0;
}

atoi

代码里面涉及到了atoi这个函数,简单地讲就是可以把字符串类型转换成int型。

用time来作为传入srand的参数

因为时间是无时无刻都走的,用这个参数的话能够保证每一的seed都不一样,所以rand后的得到的随机数也不一样了

取余符号 %

顾名思义就是取余数。
依稀能够回想起,余数是不能大于被除数的,所以想得到一定范围的数值的话,可以把这个范围作为一个值,然后用原来的值对目标范围值取余,得到的数肯定比目标范围小了,就是余数不能大于被除数的原理。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值