Algorithm: 获取指定范围的随机数(包含范围临界值)

/*
** 获取制定范围的随机数.
** 数据范围:uiStart~uiEnd (uiStart > uiEnd),随机数包括uiStart, uiEnd的取值.
*/
1
// GetRand from uiStart to uiEnd. 2 typedef unsigned int UINT; 3 UINT GetRand(UINT uiStart, UINT uiEnd) 4 { 5 if(uiStart > uiEnd) 6 { 7 cout<<"uiStart have to less than uiEnd."<<endl; 8 return -1; 9 } 10 11 return (rand() % (uiEnd - uiStart + 1) + uiStart); 12 }

 

PS: 这种方法每次生成的随机数都是一样的,即伪随机数;如果需要每次生成不一样的随机数,应该使用srand()来设置随机种子。即在循环调用之间,使用scrand(GetTickCount());来设置随机种子。

   srand(GetTickCount()); // 注释后,产生的随机数每次都一样。
    for (int i = 0; i < 10; i++)
    {
        cout<<rand()<<endl;
    }

 

posted @ 2013-03-21 17:07  nchxmoon  阅读(219)  评论(0编辑  收藏  举报