How can random numbers be generated in the C programming language?
In the C programming language, you can use the rand() function to generate random numbers. This function requires the srand() function to be called first to set the seed for the random number generator.
Here is a simple example code that demonstrates how to generate a random number between 0 and 9:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
// 设置随机数生成器的种子为当前时间
srand(time(NULL));
// 生成随机数
int randomNumber = rand() % 10;
printf("随机数:%d\n", randomNumber);
return 0;
}
In the code above, the srand(time(NULL)) function uses the current time as a seed, then calls the rand() function to generate a random number. Since rand() generates a large random integer, we use the modulo operator (%) to reduce it to a range of 0 to 9. Finally, we use the printf() function to print the generated random number.
It is important to note that each time the program runs, the generated random number sequence will be different, as the seed is set based on the system time. If you want to generate the same random number sequence each time the program runs, you can manually specify a fixed seed. For example, you can set the parameter of the srand() function to a constant, like srand(123).