Article Directory
foreword
This article mainly introduces in detail how to generate random numbers in C language.
1. Generate random numbers
Let's look at an example first: generate a random number and output it on the screen
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main()
{
srand((unsigned int)time(NULL));
int ret=rand() % 10;
printf("产生一个随机数:%d\n", ret);
return 0;
}
The result of running this code:
2.Specific analysis
It can be seen from the code that the generation of random numbers mainly depends on the two lines of code marked in red. The following is a specific analysis of these two lines of code.
1. rand function
(1 Scope
In C language we need to use the rand() function to generate random numbers.
We log in to the website https://www.cplusplus.com/ to inquire (the website mentioned here is the official C++ website, which introduces relevant grammatical functions in detail), enter the function rand
we want to query in Search , click Go and the following is Jump to the page, a part is intercepted here. From this, we have a general understanding of the rand() function. The range of random numbers it generates is 0——RAND_MAX where RAND_MAX is a value. We can copy it to the VS compiler, select the right button to go to the definition:
We can see that its value is 0x7fff
here, the 0x7fff hexadecimal, converted into binary: 32767
Therefore: the range of random numbers generated by the rand() function: 0—32767
(2) Corresponding header file
The header file corresponding to the rand() function in C language is: stdlib.h
2. The srand function
If we only use the rand() function to obtain random numbers in the process of writing programs, then we will find a problem:
when running the program, the random numbers generated each time are equal (that is, the random numbers are not random)
This is because the random number seed needs to be set with the srand() function when using the rand() function.
Similarly, we can continue to find the srand () function on this website
We jump to the time() function
When using the time() function, we usually give the value NULL (null pointer)
and need to call its corresponding header file time.h when using it
Therefore, the final use of the srand() function requires:
3. Integration
Generate random numbers in C language:
Summarize
The above is the whole content of this article, thank you for watching.