How to write code in C language to generate random numbers?

In the C language, you can use the rand() function to generate random numbers. The specific code is as follows:

#include <stdio.h>
#include <stdlib.h> // 包含rand()和srand()函数的头文件

int main() {
   int i, n;

   printf("生成随机数的个数: ");
   scanf("%d", &n);

   // 使用当前时间作为随机数种子
   srand(time(NULL));

   // 生成n个随机数并输出
   for (i = 0; i < n; i++) {
      printf("%d ", rand());
   }

   return 0;
}

In the code above, before using the rand() function to generate random numbers, it is necessary to use the srand() function to set the seed for the random numbers. Here, the current time is used as the seed to ensure that different random numbers are generated each time the program is executed. Next, n random numbers are generated and output through a loop. It is important to note that the rand() function generates random numbers in the range of 0 to RAND_MAX, where RAND_MAX is a constant representing the maximum value of random numbers.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds