C++ Random Integers: Generate with rand()

In C++, you can generate random integers using the rand() function in the standard library. The rand() function returns a pseudo-random integer between 0 and RAND_MAX. To generate a random integer within a specific range, you can use the following formula:

int randomNum = rand() % (maxNum - minNum + 1) + minNum;

The maxNum and minNum are the maximum and minimum values within the desired range. To generate different random number sequences using the rand() function, you can set the seed of the random number generator by calling srand() at the beginning of the program as shown below:

#include <iostream>
#include <cstdlib>

int main() {
    srand(time(0)); // 设置随机数生成器的种子为当前时间

    int minNum = 1;
    int maxNum = 100;
    int randomNum = rand() % (maxNum - minNum + 1) + minNum;

    std::cout << "随机整数为: " << randomNum << std::endl;

    return 0;
}

Be aware that srand(time(0)) uses the current time as the seed for the random number generator to ensure that the generated sequence of random numbers is different each time the program is run.

bannerAds