rand.c

来自「标准c库代码,可以应用于各个系统提供了大量的基本函数」· C语言 代码 · 共 109 行

C
109
字号
/*FUNCTION<<rand>>, <<srand>>---pseudo-random numbersINDEX	randINDEX	srandINDEX	_rand_rINDEX	_srand_rANSI_SYNOPSIS	#include <stdlib.h>	int rand(void);	void srand(unsigned int <[seed]>);	int _rand_r(void *<[reent]>);	void _srand_r(void *<[reent]>, unsigned int <[seed]>);TRAD_SYNOPSIS	#include <stdlib.h>	int rand();	void srand(<[seed]>)	unsigned int <[seed]>;	int _rand_r(<[reent]>);	char *<[reent]>	void _srand_r(<[data]>,<[seed]>)	char *<[reent]>;	unsigned int <[seed]>;DESCRIPTION<<rand>> returns a different integer each time it is called; eachinteger is chosen by an algorithm designed to be unpredictable, sothat you can use <<rand>> when you require a random number.The algorithm depends on a static variable called the ``random seed'';starting with a given value of the random seed always produces thesame sequence of numbers in successive calls to <<rand>>.You can set the random seed using <<srand>>; it does nothing beyondstoring its argument in the static variable used by <<rand>>.  You canexploit this to make the pseudo-random sequence less predictable, ifyou wish, by using some other unpredictable value (often the leastsignificant parts of a time-varying value) as the random seed beforebeginning a sequence of calls to <<rand>>; or, if you wish to ensure(for example, while debugging) that successive runs of your programuse the same ``random'' numbers, you can use <<srand>> to set the samerandom seed at the outset.<<_rand_r>> and <<_srand_r>> are reentrant versions of <<rand>> and<<srand>>.  The extra argument <[reent]> is a pointer to a reentrancystructure.RETURNS<<rand>> returns the next pseudo-random integer in sequence; it is anumber between <<0>> and <<RAND_MAX>> (inclusive).<<srand>> does not return a result.PORTABILITY<<rand>> is required by ANSI, but the algorithm for pseudo-randomnumber generation is not specified; therefore, even if you usethe same random seed, you cannot expect the same sequence of resultson two different systems.<<rand>> requires no supporting OS subroutines.*/#include <stdlib.h>#include <reent.h>int_DEFUN (_rand_r, (ptr),	struct _reent *ptr){  ptr->_next = (ptr->_next * 1103515245) + 12345;  return ((ptr->_next >> 16) & 0x7fff);}void_DEFUN (_srand_r, (ptr, seed),	struct _reent *ptr _AND	unsigned int seed){  ptr->_next = seed;}#ifndef _REENT_ONLYint_DEFUN_VOID (rand){  return _rand_r (_REENT);}void_DEFUN (srand, (seed),	unsigned int seed){  _srand_r (_REENT, seed);}#endif

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?