📜  cpp rand - C++ (1)

📅  最后修改于: 2023-12-03 15:14:16.351000             🧑  作者: Mango

cpp rand - C++

Introduction

rand is a standard library function in C++ that generates random numbers. It generates pseudo-random numbers, which means that the sequence of numbers generated by rand is determined by a starting point called the seed. The seed is usually set to the current time of the system clock.

Syntax
int rand();
Parameters

This function doesn't require any parameters.

Return value

The rand function returns a random integer value in the range of 0 to RAND_MAX. RAND_MAX is a constant defined in the cstdlib header file and its value is implementation dependent, but it is guaranteed to be at least 32767.

Example

Here is a simple example that generates 5 random numbers using rand.

#include <iostream>
#include <cstdlib>
#include <ctime>

int main() {
    // Seed the random number generator
    std::srand(std::time(nullptr));

    // Generate 5 random numbers
    for (int i = 0; i < 5; i++) {
        std::cout << std::rand() << std::endl;
    }

    return 0;
}

Output:

12537
24920
17322
10368
27612
Conclusion

rand is a simple yet powerful function for generating random numbers in C++. It can be used for a variety of applications, such as simulations, games, and cryptography. For more advanced random number generation, consider using the <random> header, which provides a more modern and flexible approach to random number generation.