rand

rand

Defined in header <stdlib.h>
int rand();

Returns a pseudo-random integer value between ​0​ and RAND_MAX (0 and RAND_MAX included).

srand() seeds the pseudo-random number generator used by rand(). If rand() is used before any calls to srand(), rand() behaves as if it was seeded with srand(1). Each time rand() is seeded with srand(), it must produce the same sequence of values.

rand() is not guaranteed to be thread-safe.

Parameters

(none).

Return value

Pseudo-random integer value between ​0​ and RAND_MAX, inclusive.

Notes

There are no guarantees as to the quality of the random sequence produced. In the past, some implementations of rand() have had serious shortcomings in the randomness, distribution and period of the sequence produced (in one well-known example, the low-order bit simply alternated between 1 and 0 between calls). rand() is not recommended for serious random-number generation needs, like cryptography.

POSIX requires that the period of the pseudo-random number generator used by rand is at least 232
.

POSIX offered a thread-safe version of rand called rand_r, which is obsolete in favor of the drand48 family of functions.

Example

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
 
int main(void)
{
    srand(time(0)); //use current time as seed for random generator
    int random_variable = rand();
    printf("Random value on [0,%d]: %d\n", RAND_MAX, random_variable);
}

Possible output:

Random value on [0 2147483647]: 1373858591

References

  • C11 standard (ISO/IEC 9899:2011):
    • 7.22.2.1 The rand function (p: 346)
  • C99 standard (ISO/IEC 9899:1999):
    • 7.20.2.1 The rand function (p: 312)
  • C89/C90 standard (ISO/IEC 9899:1990):
    • 4.10.2.1 The rand function

See also

seeds pseudo-random number generator
(function)
maximum possible value generated by rand()
(macro constant)
C++ documentation for rand

© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
http://en.cppreference.com/w/c/numeric/random/rand

在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号

意见反馈
返回顶部