随机的#
介绍#
The C++ Standard Library provides functions to generate pseudo-random numbers. These can be used in VEXcode IQ (2nd gen) for behaviors that require variability or chance.
以下是可用方法的列表:
数字生成器#
rand#
rand returns a random integer with no maximum.
Usage:
rand()
范围 |
描述 |
|---|---|
该方法没有参数。 |
int main() {
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();
// Display a random number
Brain.Screen.print("%d", rand());
}
int main() {
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();
// Display a random number between 0 and 100
Brain.Screen.print("%d", rand() % 101);
}
To return a random integer within a specific range, use the pattern rand() % (max - min + 1) + min.
int main() {
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();
// Display a random number between 5 and 10
Brain.Screen.print("%d", rand() % (10 - 5 + 1) + 5);
}
srand#
srand sets the starting value, seed, used by the pseudo-random number generator in the rand function.
Usage:
srand()
范围 |
描述 |
|---|---|
|
The starting seed value. |
int main() {
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();
// Use the same seed for random number
srand(1);
Brain.Screen.print("%d", rand() % 100);
}