How to write code for generating random numbers in the C language?
In C language, the rand() function can be used to generate random numbers. This function will return a random integer ranging from 0 to RAND_MAX. To generate random numbers within a specific range, you can use the modulus operator to perform a modulus operation on the return value of the rand() function.
Here is an example code that generates 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));
printf("随机数:");
for(int i = 0; i < count; i++) {
int num = (rand() % (upper - lower + 1)) + lower;
printf("%d ", num);
}
printf("\n");
return 0;
}
The above code will generate five random numbers between 1 and 100 and print them out.
Before using the rand() function, it is necessary to first use the srand() function to set a random number seed. Here, the time(0) function is used to obtain the current time as the seed, to ensure that a different random number sequence is generated each time the program is run.