隨機的#

介紹#

C++標準函式庫提供了產生偽隨機數的函式。這些函數可用於VEXcode IQ中需要變化性或隨機性的行為模擬。

函數#

<cstdlib> 庫包含以下函數:

  • rand — 傳回一個隨機整數。

  • srand — 設定隨機種子。

rand#

傳回 0 到 2,147,483,647 之間的隨機整數。

Available Functions
int rand();

Parameters

此函數不接受任何參數。

Return Values

傳回 0 到 2,147,483,647 之間的隨機整數。

Notes
  • 若要傳回限定範圍內的隨機整數,請使用模式 rand() % max。

  • 若要傳回特定範圍內的隨機整數,請使用模式 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#

設定 rand 函數中偽隨機數產生器要使用的種子。

Available Functions
void srand( unsigned int seed );

Parameters

範圍

類型

描述

seed

unsigned int

初始種子值。

Return Values

此函數不傳回值。

Notes
  • 在專案開始不久,呼叫 srand 一次,然後再呼叫 rand無需在每調用 rand之前都調用它。

  • 如果從未呼叫過 srand ,程式的行為就如同使用了 srand(1) 。這意味著每次運行 `rand rand 都會產生相同的數字序列。

  • 為了在每次專案運行時獲得不同的結果,請使用在運行之間會改變的值作為種子,例如 Brain 的計時器。

  • 為了每次都得到相同的結果(對測試很有用),使用固定的數字作為種子,例如 srand(1)。

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