循环里srand(time(0))和rand()为什么在执行时显示的是几个同样的数,而在单步调试时每次显示不同数字呢;
时间:2011-12-21
来源:互联网
#include <iostream>
#include <cstdlib>
#include <ctime>
const int MAX=10;
int main()
{
int times,i=0;
std::cin>>times;
while(i!=5)
{
srand(time(0));
int hello=rand();
std::cout<<hello%MAX<<" ";
i++;
}
return 0;
}
上面的代码为什么在直接执行时每次循环都产生几个相同的数字,而如果下断点,单步的话,每次又显示不同的数字呢
#include <cstdlib>
#include <ctime>
const int MAX=10;
int main()
{
int times,i=0;
std::cin>>times;
while(i!=5)
{
srand(time(0));
int hello=rand();
std::cout<<hello%MAX<<" ";
i++;
}
return 0;
}
上面的代码为什么在直接执行时每次循环都产生几个相同的数字,而如果下断点,单步的话,每次又显示不同的数字呢
作者: zoelva 发布时间: 2011-12-21
不要每次rand()前都重新srand(),因为你这样的话每次都重置第一个随机数(即种子),而time()返回的数值不会相差很大,所以第一个数由于time()返回值过于接近而不随机
最好从第二次rand()开始取数,而srand()只用一次
最好从第二次rand()开始取数,而srand()只用一次
作者: yisikaipu 发布时间: 2011-12-21
C:\Program Files\Microsoft Visual Studio 10.0\VC\crt\src\rand.c
C/C++ code
C/C++ code
/*** *rand.c - random number generator * * Copyright (c) Microsoft Corporation. All rights reserved. * *Purpose: * defines rand(), srand() - random number generator * *******************************************************************************/ #include <cruntime.h> #include <mtdll.h> #include <stddef.h> #include <stdlib.h> /*** *void srand(seed) - seed the random number generator * *Purpose: * Seeds the random number generator with the int given. Adapted from the * BASIC random number generator. * *Entry: * unsigned seed - seed to seed rand # generator with * *Exit: * None. * *Exceptions: * *******************************************************************************/ void __cdecl srand ( unsigned int seed ) { _getptd()->_holdrand = (unsigned long)seed; } /*** *int rand() - returns a random number * *Purpose: * returns a pseudo-random number 0 through 32767. * *Entry: * None. * *Exit: * Returns a pseudo-random number 0 through 32767. * *Exceptions: * *******************************************************************************/ int __cdecl rand ( void ) { _ptiddata ptd = _getptd(); return( ((ptd->_holdrand = ptd->_holdrand * 214013L + 2531011L) >> 16) & 0x7fff ); }
作者: zhao4zhong1 发布时间: 2011-12-21
相关阅读 更多
热门阅读
-
office 2019专业增强版最新2021版激活秘钥/序列号/激活码推荐 附激活工具
阅读:74
-
如何安装mysql8.0
阅读:31
-
Word快速设置标题样式步骤详解
阅读:28
-
20+道必知必会的Vue面试题(附答案解析)
阅读:37
-
HTML如何制作表单
阅读:22
-
百词斩可以改天数吗?当然可以,4个步骤轻松修改天数!
阅读:31
-
ET文件格式和XLS格式文件之间如何转化?
阅读:24
-
react和vue的区别及优缺点是什么
阅读:121
-
支付宝人脸识别如何关闭?
阅读:21
-
腾讯微云怎么修改照片或视频备份路径?
阅读:28