Τυχαίος#

Εισαγωγή#

Η Βιβλιοθήκη Τυποποιημένων Εκδόσεων 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 και 2.147.483.647.

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’s timer.

  • 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);