C Random Numbers: Generate with rand()

In C language, you can use the standard library function rand() to generate random numbers. Below is a simple example demonstrating how to use rand() to generate a random number:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
   int i, n;
   // 使用当前时间作为随机数种子
   srand(time(0));

   printf("生成10个随机数:\n");

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

   return 0;
}

It is important to note that the rand() function generates a pseudo-random number, which will produce the same random number sequence every time the program runs. To avoid this, you can use the srand() function to set a different seed before using rand(). In the example above, by using the time(0) function to get the current time as the seed, you can ensure that a different random number sequence is generated each time the program is run.

bannerAds