Fork me on GitHub

一 前记:

  c语言中需要用到随机值得时候,每次都自己写,这样太浪费效率了,这次遇到了一个经典的代码,就珍藏起来吧。

 

二 实例分析:

 

 1     #include <stdio.h>
 2 
 3     int random_number(int min_num, int max_num);
 4 
 5     int main(void)
 6     {
 7         printf("Min : 1 Max : 40 %d\n", random_number(1,40));
 8         printf("Min : 100 Max : 1000 %d\n",random_number(100,1000));
 9         return 0;
10     }
11 
12     int random_number(int min_num, int max_num)
13     {
14         int result = 0, low_num = 0, hi_num = 0;
15 
16         if (min_num < max_num)
17         {
18             low_num = min_num;
19             hi_num = max_num + 1; // include max_num in output
20         } else {
21             low_num = max_num + 1; // include max_num in output
22             hi_num = min_num;
23         }
24 
25         srand(time(NULL));
26         result = (rand() % (hi_num - low_num)) + low_num;
27         return result;
28     }

    

   这段代码真是简洁明了,让人不忍心丢弃啊。

 

posted on 2020-11-04 10:54  虚生  阅读(467)  评论(0编辑  收藏  举报