C++产生随机数

来源:互联网 发布:万能视频修复软件 编辑:程序博客网 时间:2024/06/13 22:05
 C++怎样产生随机数:这里要用到的是rand()函数srand()函数,C++里没有自带的random(int number)函数。

(1) 如果你只要产生随机数而不需要设定范围的话,你只要用rand()就可以了:rand()会返回一随机数值, 范围在0至RAND_MAX 间。RAND_MAX值至少为32767。
例如:

[cpp] view plaincopy
  1. #include<stdio.h>  
  2. #include <iostream>  
[cpp] view plaincopy
  1. int _tmain(int argc, _TCHAR* argv[])  
  2. {  
  3.        for(int i=0;i<10;i++)  
  4.              cout << rand() << endl;  
  5. }  

 

(2) 如果你要随机生成一个在一定范围的数,

例如:随机生成10个0~99的数:

[cpp] view plaincopy
  1. #include<stdio.h>  
  2. #include <iostream>  
[cpp] view plaincopy
  1. int _tmain(int argc, _TCHAR* argv[])  
  2.   
  3. {  
  4.      for(int x=0;x<10;x++)  
  5.            cout << rand()%100 << " ");  
  6. }  


总之,产生a~b范围的随机数,可用: a+rand()%(b-a+1)

(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>

例如:

[cpp] view plaincopy
  1. #include<stdio.h>  
  2. #include<time.h>                                  
  3.   
  4. #include <iostream>  
  5.   
  6. int _tmain(int argc, _TCHAR* argv[])  
  7. {  
  8.  srand((unsigned)time(NULL)); //srand((unsigned)time(0))   srand((int)time(0) 均可  
  9.   
  10. for(int i=0;i<10;i++)   
  11.   
  12. cout << rand() << endl;  
  13.   
  14. }  

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

原创粉丝点击