How to use the rand function in the C language?
In C language, to use the random function rand(), you need to include the header file stdlib.h. You can then use the following code to generate a random number:
#include <stdio.h>
#include <stdlib.h>
int main() {
int randomNumber;
// 生成一个0到RAND_MAX之间的随机数
randomNumber = rand();
printf("随机数为: %d", randomNumber);
return 0;
}
To generate a random number between 0 and N, you can use the modulus operator.
#include <stdio.h>
#include <stdlib.h>
int main() {
int randomNumber, N;
// 设定N的值
N = 100;
// 生成一个0到N之间的随机数
randomNumber = rand() % (N + 1);
printf("0到%d之间的随机数为: %d", N, randomNumber);
return 0;
}
It is important to note that the random numbers generated each time the program runs are the same because the seed of the random numbers has not changed. The srand() function can be used to set the seed of the random numbers, usually by using the system time as the seed to ensure that different random numbers are generated each time.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int randomNumber, N;
// 使用系统时间作为种子
srand(time(0));
// 设定N的值
N = 100;
// 生成一个0到N之间的随机数
randomNumber = rand() % (N + 1);
printf("0到%d之间的随机数为: %d", N, randomNumber);
return 0;
}
The above is the basic method of generating random numbers using the rand() function, which can be further customized based on specific needs.