C++ 随机数

C++ 中生成随机数需用到srand() 和 rand() 两个函数 ( #include<cstdlib> )

步骤一: 使用 void srand(time(NULL) );设置seed ,一般time(NULL) ( #include<ctime>) 获取当前时间 作为种子;

步骤二:使用 int  rand() ; 获得一个[0,RAND_MAX(0x7fff)) 直接的随机整数。

     要想取得[a,b)之间的随机整数,使用(rand()%(b-a))+ a,结果包含 a 而不含 b 。

例子:

// C++随机函数(VC program) 
#include <stdio.h> 
#include <iostream> 
#include <ctime> 
using namespace std; 
int main(int argc, char* argv[]) 
{    
srand( (unsigned)time( NULL ) );
//srand()函数产生一个以当前时间开始的随机种子. int a=5,b=10;    for (int i=0;i<10;i++)    cout<<rand()%(b-a)+a <<endl;//MAX为最大值,其随机域为[a,b)    return 0; }

 

 

posted on 2012-08-21 21:32  没有什么能够阻挡  阅读(147)  评论(0编辑  收藏  举报

导航