srand(time(0));这句话的工作原理是什么??

iwodgirl 2005-10-25 06:39:37
#include<iostream.h>
#include<stdlib.h>
#include<time.h>
main()
{
int a[10][10];
int b[10];
int i,j,equ=0;
srand(time(0)); //这句话的工作原理是什么??

for(i=0;i<10;i++)
for(j=0;j<10;j++)
a[i][j]=i*10+j;

for(i=0;i<10;i++,equ=0){
do{
b[i]=a[rand()%10][rand()%10];
for(j=0;j<i;j++)
if(b[i]==b[j])equ=1;
}while(equ);
}

for(i=0;i<10;i++)
cout<<b[i]<<endl;

cin>>i;//起暂停作用
}

以上程序,如果不用srand(time(0)),程序会进入死循环

...全文
835 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
iwodgirl 2005-10-25
  • 打赏
  • 举报
回复
//大家看看下面的程序,最好运行一下,再教教我《如题目.

#include<iostream.h>
#include<stdlib.h>

main()
{
int a[10][10];
int i,j,equ=0;

for(i=0;i<10;i++)
for(j=0;j<10;j++)
a[i][j]=i*10+j;

for(i=0;i<10;i++)
{
cout<<endl;
for(j=0;j<10;j++)
cout<<a[rand()%10][rand()%10]<<" ";
}


cin>>i;//起暂停作用
}

majinyi 2005-10-25
  • 打赏
  • 举报
回复
是一个随机数种子。在用随机数之前必须给他一个种子,要不然的话每次得到的随机数列都是一样的
ErikChen1985 2005-10-25
  • 打赏
  • 举报
回复
Example

/* RAND.C: This program seeds the random-number generator
* with the time, then displays 10 random integers.
*/

#include <stdlib.h>
#include <stdio.h>
#include <time.h>

void main( void )
{
int i;

/* Seed the random-number generator with current time so that
* the numbers will be different every time we run.
*/
srand( (unsigned)time( NULL ) );

/* Display 10 numbers. */
for( i = 0; i < 10;i++ )
printf( " %6d\n", rand() );
}


Output

6929
8026
21987
30734
20587
6699
22034
25051
7988
10104

MSDN中的例子
yangyzqo 2005-10-25
  • 打赏
  • 举报
回复
学习
liuwei73656 2005-10-25
  • 打赏
  • 举报
回复
如果不设种子,那产生的随机数序列是一样的
steel007 2005-10-25
  • 打赏
  • 举报
回复
srand()是给随机数产生器一个种子,time(NULL)就是把当前的时间值作为种子。
如果不设种子,那~~~~随机数产生的可能就会有问题
junnyfeng 2005-10-25
  • 打赏
  • 举报
回复
The rand() function uses a multiplicative congruential
random-number generator with period 2**32 that returns suc-
cessive pseudo-random numbers in the range of 0 to RAND_MAX
(defined in <stdlib.h>).

The srand() function uses the argument seed as a seed for a
new sequence of pseudo-random numbers to be returned by sub-
sequent calls to rand(). If srand() is then called with the
same seed value, the sequence of pseudo-random numbers will
be repeated. If rand() is called before any calls to
srand() have been made, the same sequence will be generated
as when srand() is first called with a seed value of 1.

64,282

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧