How can we implement automatic generation of random numbers in C language?
In C language, the rand() function can be used to generate random numbers. You need to include the header file stdlib.h and use the srand() function to set the seed for the random numbers.
Here is an example code that can generate random numbers within a specified range.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int lower = 1, upper = 100, count = 5;
// 设置随机数的种子为当前时间
srand(time(0));
for(int i = 0; i < count; i++) {
int num = (rand() % (upper - lower + 1)) + lower;
printf("%d\n", num);
}
return 0;
}
In the code above, the range and quantity of random numbers generated are determined by setting lower, upper, and count. The rand() function generates a random number between 0 and RAND_MAX, which is then calculated to fall within the specified range through modulo and offset. Each time the program is run, the random number seed is set to the current time, ensuring that every generated random number is different.