Chinaunix首页 | 论坛 | 博客
  • 博客访问: 203933
  • 博文数量: 87
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 798
  • 用 户 组: 普通用户
  • 注册时间: 2015-01-14 14:54
文章分类

全部博文(87)

文章存档

2015年(87)

我的朋友

分类: C/C++

2015-08-21 08:42:58

C/C++怎样产生随机数:这里要用到的是rand()函数, srand()函数,C语言/C++里没有自带的random(int number)函数。
(1)  如果你只要产生随机数而不需要设定范围的话,你只要用rand()就可以了:rand()会返回一随机数值, 范围在0至RAND_MAX 间。RAND_MAX定义在stdlib.h, 其值为2147483647。
例如:

点击(此处)折叠或打开

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

  3. int main(int argc, char *argv[])
  4. {
  5.     int i=0;
  6.     for(i=0; i<10; i++)
  7.     {
  8.         printf("%d ", rand());
  9.     }
  10.     printf("\n");
  11.    
  12.    return 0;
  13. }
(2)  如果你要随机生成一个在一定范围的数,你可以在宏定义中定义一个random(int number)函数,然后在main()里面直接调用random()函数:
例如:随机生成10个0~100的数:

点击(此处)折叠或打开

  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #define random(x) (rand()%x)

  4. int main(int argc, char *argv[])
  5. {
  6.     int i=0;
  7.     for(i=0; i<10; i++)
  8.     {
  9.         printf("%d ", random(100));
  10.     }
  11.     printf("\n");
  12.    
  13.    return 0;
  14. }
(3)但是上面两个例子所生成的随机数都只能是一次性的,如果你第二次运行的时候输出结果仍和第一次一样。这与srand()函数有关。srand()用来设置rand()产生随机数时的随机数种子。在调用rand()函数产生随机数前,必须先利用srand()设好随机数种子(seed), 如果未设随机数种子, rand()在调用时会自动设随机数种子为1。上面的两个例子就是因为没有设置随机数种子,每次随机数种子都自动设成相同值1 ,进而导致rand()所产生的随机数值都一样。

srand()函数定义 : void srand (unsigned int seed);
通常可以利用geypid()或time(0)的返回值来当做seed
如果你用time(0)的话,要加入头文件#include<time.h>

例如:

点击(此处)折叠或打开

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

  4. #define random(x) (rand()%(x))

  5. int main(int argc, char *argv[])
  6. {
  7.     int i=0;
  8.     srand((unsigned int)time(NULL));
  9.     for(i=0; i<10; i++)
  10.     {
  11.         printf("%d ",random(100));
  12.     }
  13.     printf("\n");
  14.     
  15.     return 0;
  16. }

这样两次运行的结果就会不一样了!!

阅读(788) | 评论(0) | 转发(0) |
0

上一篇:2015年华为机试

下一篇:矩阵走法问题

给主人留下些什么吧!~~