产生真正的随机数

         srand((unsigned)time(NULL))使用系统定时/计数器的值作为随机种子。每个种子对应一组根据算法预先生成的随机数,所以,在相同的平台环境下,不同时间产生的随机数会是不同的,若将srand(unsigned)time(NULL)改为srand(TP)(TP为任一常量),则无论何时运行、运行多少次得到的“随机数”都会是一组固定的序列。


        time(0)被定义成长整型,它返回从1970年1月1日零时零分零秒到目前为止所经过的时间,单位为秒。

#include
#include
using namespace std;

int main()
{
srand((unsigned)time(0))  ||  srand((unsigned)time(NULL)) ;
int a=rand()%n+k ;
return 0;
}
生成[k,k+n-1]范围的随机数。

PS:如果仍然觉得时间间隔太小,可以在(unsigned)time(0)或者(unsigned)time(NULL)后面乘上某个合适的整数。
例如:srand((unsigned)time(NULL)*10)。

你可能感兴趣的:(杂文)