随机的#
介绍#
C++ 标准库提供了生成伪随机数的函数。这些函数可用于 VEXcode IQ(第二代)中需要变化性或随机性的行为。
以下是可用方法的列表:
数字生成器#
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()
范围 |
描述 |
---|---|
该方法没有参数。 |
int main() {
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();
// Use the same seed for random number
srand(1);
Brain.Screen.print("%d", rand() % 100);
}