initstate()
告诉 random 使用什么缓冲区来存储下一个随机数的信息。random()
由于缓冲区中的信息state1[256]
已更改,您在调用中会得到不同的答案。查看以下代码的输出:
#define LEN (32)
void print_hex( char *b)
{
int i;
for( i=0; i < LEN; i++) printf("%02x ",((unsigned char *)b)[i]);
printf("\n");
}
main()
{
char state1[256], state2[256], tmp[256];
initstate( 42, state2, LEN);
initstate( 62, state1, LEN) ;
printf("buffer before random():\n");
print_hex( state1 ) ;
printf("%10ld\n", random());
printf("buffer after random():\n");
print_hex( state1 ) ;
setstate( state2 ); // Now we are free to copy data from state1
printf("buffer after setstate():\n");
print_hex( state1 ) ;
memcpy( tmp, state1, 256);
printf("copied to tmp\n");
setstate( state1 ); // Go on with original sequence
printf("next random():\n") ;
printf("%10ld\n", random());
printf("next random():\n") ;
printf("%10ld\n", random());
setstate( state2 ) ; // Again, this allows us to play with data in state1
memcpy( state1, tmp, 256);
setstate( state1 ) ;
printf("back copy:\n");
printf("random() after copy:\n") ;
printf("%10ld\n", random());
printf("next random():\n") ;
printf("%10ld\n", random());
}
这给出了输出:
buffer before random():
01 00 00 00 e7 22 1d 21 f1 62 9c 90 89 72 b5 89 35 2b 97 b5 76 8c ff a8 56 14 14 7b ba 19 d9 f7
1801070350
buffer after random():
01 00 00 00 e7 22 1d 21 f1 62 9c 90 89 72 b5 89 1c 4e b4 d6 76 8c ff a8 56 14 14 7b ba 19 d9 f7
buffer after setstate():
06 00 00 00 e7 22 1d 21 f1 62 9c 90 89 72 b5 89 1c 4e b4 d6 76 8c ff a8 56 14 14 7b ba 19 d9 f7
copied to tmp
next random():
483260339
next random():
40158063
back copy:
random() after copy:
483260339
next random():
40158063
可以看到第一次调用后random()
缓冲区的内容发生了state1
变化。random()
使用该区域来存储其状态。此状态被复制到缓冲区tmp
。稍后我们将其复制回state1
,并获得相同的随机数序列。请注意,在您复制到应该用于随机数的缓冲区或从缓冲区复制之前,您必须使用or告诉random()
停止使用该缓冲区。原因是当被调用时,旧缓冲区被修改以允许它再次被加载。setstate()
initstate()
setstate()
setstate()
因此,要获得与原始问题相同的答案,您必须使用:
unsigned int seed1 = 42;
char state1[256], tmp[256];
initstate(seed1, state1, 256);
printf("%10ld\n", random());
initstate( 0, tmp, 256); // <- notice this
setstate( state1 ) ;
printf("%10ld\n", random());