Home C&C++函数库 c++ 语法 程序源码 Linux C库

rand

函数   <cstdlib>

int rand (void);

生成随机数

返回一个范围在0和RAND_MAX之间的伪随机整数。
这个数字是由一个算法生成的,该算法在每次调用时返回一个明显不相关的数字序列。 该算法使用种子来生成序列,应该使用srand函数将序列初始化为特定的值。

RAND_MAX是在<cstdlib>中定义的常量。
在确定的范围内使用rand生成普通伪随机数的一个典型方法是用范围跨度对返回值取模,然后加上该范围的初始值:

v1 = rand() % 100;         // v1 in the range 0 to 99
v2 = rand() % 100 + 1;     // v2 in the range 1 to 100
v3 = rand() % 30 + 1985;   // v3 in the range 1985-2014


但是请注意,这个模运算并不会在空间中生成均匀分布的随机数(因为在大多数情况下, 这个运算会使更小的数字更有可能出现)。

c++支持大量强大的工具来生成随机数和伪随机数(更多信息请参见<random>)。

☲  参数



none

☉  返回值



一个0和RAND_MAX之间的整数。

☣  示例



/* rand example: guess the number */
#include <stdio.h>      /* printf, scanf, puts, NULL */
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */

int main ()
{
  int iSecret, iGuess;

  /* initialize random seed: */
  srand (time(NULL));

  /* generate secret number between 1 and 10: */
  iSecret = rand() % 10 + 1;

  do {
    printf ("Guess the number (1 to 10): ");
    scanf ("%d",&iGuess);
    if (iSecret<iGuess) puts ("The secret number is lower");
    else if (iSecret>iGuess) puts ("The secret number is higher");
  } while (iSecret!=iGuess);

  puts ("Congratulations!");
  return 0;
}

在这个例子中,随机种子被初始化为一个表示当前时间(调用time)的值,以便在程序每次运行时生成一个不同的值。

可能的输出:
Guess the number (1 to 10): 5
The secret number is higher
Guess the number (1 to 10): 8
The secret number is lower
Guess the number (1 to 10): 7
Congratulations!

↭  兼容性



在C语言中,rand使用的生成算法只能通过调用这个函数来实现。在c++中, 这个约束是宽松的,并且允许库实现在其他情况下扩展生成(例如调用<random>的元素)。

↭  数据竞争



该函数访问和修改内部状态对象,这可能会导致rand或srand的并发调用发生数据竞争。

一些库提供了一个替代函数,显式地避免了这种数据竞争:rand_r(不可移植)。

c++库实现允许保证调用该函数时不存在数据竞争。

❆  异常(c++)



无抛出保证:此函数从不抛出异常。

🍄  另请参阅



srand 初始化随机数生成器(function )

联系我们 免责声明 关于CandCplus 网站地图