Chinaunix首页 | 论坛 | 博客
  • 博客访问: 389703
  • 博文数量: 75
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 645
  • 用 户 组: 普通用户
  • 注册时间: 2015-06-03 18:24
文章分类

全部博文(75)

文章存档

2019年(1)

2018年(20)

2017年(14)

2016年(10)

2015年(30)

分类: LINUX

2018-02-25 22:20:19

1、函数
int rand(void);
   The rand() function returns a pseudo-random integer in the range 0 to RAND_MAX inclusive (i.e.,
       the mathematical range [0, RAND_MAX]).(RAND_MAX定义在stdlib.h,其值为2147483647)
备注:在调用rand函数前,必须先利用srand设置好随机数种子。如果未设置随机数种子,rand调用时,会自动设置随机数种子为1
例子:

点击(此处)折叠或打开

  1. #include <stdio.h>
  2. #include <stdlib.h>

  3. /**/
  4. int main(int argc, char **argv)
  5. {
  6.     int i;

  7.     /**/
  8.     for(i = 0; i < 10; i++)
  9.     {
  10.         printf("index:%d rand:%d\n", i, rand());
  11.     }
  12.     printf("\n");

  13.     /*设置随机数种子为1*/
  14.     printf("set the random number seed to 1\n");
  15.     srand(1);
  16.     for(i = 0; i < 10; i++)
  17.     {
  18.         printf("index:%d rand:%d\n", i, rand());
  19.     }

  20.     return 0;
  21. }
执行结果:


通常我们会使用时间作为随机数的种子,这样每次调用后产生的随机数都不一样。
例子

点击(此处)折叠或打开

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>

  4. /**/
  5. int main(int argc, char **argv)
  6. {
  7.     int i;
  8.     srand(time(NULL));

  9.     /**/
  10.     for(i = 0; i < 10; i++)
  11.     {
  12.         printf("index:%d rand:%d\n", i, rand());
  13.     }

  14.     return 0;
  15. }
运行结果












阅读(848) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~