Generate Random Numbers in C
In C language, we can use the rand() function to generate random numbers.
First, it is necessary to include the stdlib.h header file, which contains the declaration of the rand() function.
Next, you can use the srand() function to set the seed for the random number generator. The seed is an integer that can be obtained by using the time() function to get the current time as the seed. For example:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int i;
srand(time(0)); // 设置随机数生成器的种子为当前时间
for (i = 0; i < 10; i++) {
printf("%d\n", rand()); // 生成随机数并输出
}
return 0;
}
In the above example, the current time is used as a seed by calling srand(time(0)), then random numbers are generated using rand() and 10 of them are output in a loop.
It is important to note that random numbers generated by the rand() function are pseudo-random; the sequence of random numbers generated each time the program runs will be the same unless a different seed is set using the srand() function.