How is the random function used in C++?
In C++, including the header file is necessary when using the random number function.
- Generate a random integer between 0 and RAND_MAX using the rand() function.
- Set the random number seed using the srand(seed) function, where seed is an integer value used to initialize the random number generator.
Example code:
#include <iostream>
#include <cstdlib>
int main() {
// 设置随机数种子
srand(42);
// 生成随机整数
int randomNum = rand();
std::cout << "Random number: " << randomNum << std::endl;
return 0;
}
- Generate a random integer between 0 and range-1 using rand() % range.
- Generate a random integer between 0 and a specified range using rand() divided by (RAND_MAX divided by the range plus 1).
Example code:
#include <iostream>
#include <cstdlib>
int main() {
// 设置随机数种子
srand(42);
// 生成0到9之间的随机整数
int randomNum1 = rand() % 10;
std::cout << "Random number (0-9): " << randomNum1 << std::endl;
// 生成1到10之间的随机整数
int randomNum2 = rand() % 10 + 1;
std::cout << "Random number (1-10): " << randomNum2 << std::endl;
return 0;
}
- Generate a random integer between 0 and RAND_MAX using the rand() function, then divide it by RAND_MAX to obtain a random floating-point number between 0 and 1.
Example code:
#include <iostream>
#include <cstdlib>
int main() {
// 设置随机数种子
srand(42);
// 生成0到1之间的随机浮点数
double randomNum = static_cast<double>(rand()) / RAND_MAX;
std::cout << "Random number (0-1): " << randomNum << std::endl;
return 0;
}