How do you randomly generate a number in C language?
In C language, the rand() function can be used to generate a random number. It is important to note that each time the program runs, the random number generated by the rand() function will be the same. To avoid this situation, you can call the srand() function before using the rand() function to set the seed for the random number. Here is an example code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
// 设置随机数种子
srand(time(NULL));
// 产生一个随机数
int randomNumber = rand();
printf("随机数为:%d\n", randomNumber);
return 0;
}
In the above code, the srand(time(NULL)) function sets the random seed to the current time, ensuring that each time the program runs, a different random number is generated. It then uses the rand() function to generate a random number and prints it out using printf().