注册 登录
编程论坛 C++教室

请教一个小问题

wzhengxiang1985 发布于 2008-08-15 00:51, 518 次点击
各位大虾,我是个C++的爱好者,想请教一下下面的问题:
#include<iostream>
#include<ctime>
#include<cstdlib>
using std::cout;
using std::cin;
using std::endl;
using std::rand;
using std::srand;
using std::time;
main(){
       cout<<"out 5 numeber between 1 and 49:";
       const int number=5;
       const int limits=49;
       int i=1;
       //srand((unsigned int)time(0));  屏蔽此行时候,运行的结果每次都一样;
       for(;i<=number;i++)
       {
       //srand((unsigned int)time(0));屏蔽此行时候,运行时每次结果都不一样
       cout<<static_cast<int>(1+(limits-1)*static_cast<long>(rand())/RAND_MAX)<<" ";   
       }
       cout<<endl;
       system("pause");
       }   
想请大虾分析一下,谢谢
1 回复
#2
xxp272008-08-15 10:42
srand函数是随机数发生器的初始化函数,原型:
void srand(unsigned seed);
它需要提供一个种子,如:
srand(1);
直接使用1来初始化种子。
不过常常使用系统时间来初始化,即使用
time函数来获得系统时间,它的返回值为从 00:00:00 GMT, January 1, 1970
到现在所持续的秒数,然后将time_t型数据转化为(unsigned)型在传给srand函数,即:
srand((unsigned) time(&t));
还有一个经常用法,不需要定义time_t型t变量,即:
srand((unsigned) time(NULL));
直接传入一个空指针,因为你的程序中往往并不需要经过参数获得的t数据。

所以你删掉以后,结果就一样了
而且你要得到1~49之间的随机数只要rand%49+1就可以了

[[it] 本帖最后由 xxp27 于 2008-8-15 10:49 编辑 [/it]]
1