Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and medical aesthetics - How to generate random numbers in C language
How to generate random numbers in C language
In actual programming, we often need to generate random numbers. In C language, we usually use rand method to generate random numbers. Before calling rand, we need to call srand to initialize the random number seed.

Computer: Huawei MateBook 14

System: Windows 10

Software: Notepad++and other editors and gcc compiler 1.0.

1. Use the rand function to generate a random number, and rand randomly generates an integer between 0 and 0~RAND_MAX. As shown in the figure below, we directly use the rand method to generate 10 random numbers.

2. The random number will be generated after the program runs, but the problem of using rand directly is that the random number generated next time the program is called is the same as last time. Therefore, although the rand function generates random numbers, it can also be said to be pseudo-random. Because every time it is called, the number generation order is fixed.

3. In order to generate different random numbers in each call, the random number seed is initialized with srand function. As long as the random number seed changes, the generated random number will change. Usually, srand uses the current time as the seed.

4. But is it safe to use time as a random number seed? Our current program executes too fast, and one second is too long for a computer. We define the operation of generating random numbers as a function and then call the function twice to see that the generated random numbers are still the same.

5. The optimization function is also relatively simple. On the basis of using time, we also added a fixed serial number. This can ensure that even if it is called many times in the same second, the seeds of random numbers are different.

6. Usually, we need to get a certain range of random numbers. So after generating random numbers, we use modular operation to get the data in the corresponding range. Such as generating random numbers from 0 to 100.