随机的#

介绍#

C++标准库提供了生成伪随机数的函数。这些函数可用于VEXcode IQ中需要变化性或随机性的行为模拟。

函数#

The <cstdlib> library includes the following functions:

  • rand — Returns a random integer.

  • srand — Sets the random seed.

rand#

返回 0 到 2,147,483,647 之间的随机整数。

Available Functions
int rand();

Parameters

此函数不接受任何参数。

Return Values

返回 0 到 32767 之间的随机整数。

Notes
  • To return a random integer within an exclusive limit, use the pattern rand() % max.

  • To return a random integer within a specific range, use the pattern rand() % (max - min + 1) + min.

Examples
// Display a random number
Brain.Screen.print("%d", rand());

// Display a random number between 0 and 100
Brain.Screen.print("%d", rand() % 101);

// Display a random number between 5 and 10
Brain.Screen.print("%d", rand() % (10 - 5 + 1) + 5);

srand#

Sets the seed to be used by the pseudo-random number generator in the rand function.

Available Functions
void srand( unsigned int seed );

Parameters

范围

类型

描述

seed

unsigned int

初始种子值。

Return Values

此函数不返回值。

Notes
  • Call srand only once, near the start of your project, before calling rand. You do not need to call it before every rand.

  • If srand is never called, the program behaves as if srand(1) was used. This means rand produces the same sequence of numbers every time the project runs.

  • 为了在每次项目运行时获得不同的结果,请使用在运行之间会改变的值作为种子,例如 Brain 的计时器

  • To get the same results every time (useful for testing), seed with a fixed number such as srand(1).

Examples
// Use the same seed for random number
srand(5);
Brain.Screen.print("%d", rand() % 100);