How can C language generate random numbers?
In C language, the rand() function can be used to generate random numbers. The rand() function returns a random integer within the range of 0 to RAND_MAX. To get random numbers within a specific range, the modulo operation can be used to adjust the range. For example, to generate a random number between 1 and 100, the following code can be used:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int num;
// 使用当前时间作为随机数种子
srand(time(0));
// 生成1到100之间的随机数
num = rand() % 100 + 1;
printf("随机数: %d\n", num);
return 0;
}
In the program above, the srand(time(0)) function is used to set the current time as the seed for the random number generator, ensuring that different random numbers are generated each time the program runs. Then, the rand() % 100 + 1 is used to limit the generated random number between 1 and 100. Finally, the printf function is used to print the generated random number.