How to use the random function “rand” in C++?
In C++, you can use the rand function to generate random numbers. The basic steps to use the rand function are as follows:
- Include header files: Include header files in the program.
- Set a random seed: At the beginning of the program, set a random seed by calling the srand function. You can use the time function to get the current time as the seed, to ensure that a different random number sequence is generated each time the program is run. Example code:
#include <cstdlib>
#include <ctime>
int main() {
srand(time(0)); // 设置随机数种子为当前时间
// ...
return 0;
}
- Generate random numbers by calling the rand function, which will return an integer between 0 and RAND_MAX. To narrow down the range of random numbers generated, you can use the modulus operator. Below is an example code:
int randomNumber = rand() % range;
In this case, the range is the range in which you want to generate random numbers. For example, if you want to generate a random number between 0 and 9, you can set the range to be 10.
The complete example code is shown below:
#include <iostream>
#include <cstdlib>
#include <ctime>
int main() {
srand(time(0)); // 设置随机数种子为当前时间
int randomNumber = rand() % 10; // 生成一个0到9之间的随机数
std::cout << "随机数:" << randomNumber << std::endl;
return 0;
}
The code will generate a random number between 0 and 9 and display it on the screen.