How to generate random numbers in the C language?
In C language, you can utilize the rand() function to generate random numbers. The specific method is as follows:
- Include the header file: The first step is to include the stdlib.h header file in the program.
#include <stdlib.h>
- Setting the seed value: Use the srand() function to set a seed value. Typically, the current time can be used as the seed value using the time() function.
srand(time(NULL));
- Generate random numbers: Use the rand() function to generate random numbers. When you call the rand() function, it will return a random integer between 0 and RAND_MAX (usually 32767).
int random_number = rand();
- Limit range: To generate random numbers within a specific range, you can achieve this by using modulo operation and offset. For example, to generate a random number between 1 and 100, you can use the following code:
int random_number = rand() % 100 + 1;
The complete example code is as follows:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
// 设置种子值
srand(time(NULL));
// 生成随机数
int random_number = rand();
// 限定范围
random_number = random_number % 100 + 1;
// 输出结果
printf("Random number: %d\n", random_number);
return 0;
}
The code above will generate a random number between 1 and 100, and then display it on the console.