C语言 rand srand rand_r
所属分类 c
浏览量 834
The rand() function computes a sequence of pseudo-random integers in the range of 0 to RAND_MAX
(as defined by the header file stdlib.h).
The srand() function sets its argument seed as the seed for a new sequence of pseudo-random num-bers to be returned by rand().
These sequences are repeatable by calling srand() with the same seed value.
If no seed value is provided, the functions are automatically seeded with a value of 1.
The sranddev() function initializes a seed, using the random random number device which returns good random numbers.
However, the rand() function still remains unsuitable for cryptographic use.
The rand_r() function provides the same functionality as rand().
A pointer to the context value seed must be supplied by the caller.
#include "stdio.h"
#include "stdlib.h"
int main(int argc, char *argv[]){
if (argc != 2){
printf("seed is needed\n");
exit(EXIT_FAILURE);
}
int seed = atoi(argv[1]);
printf("seed=%d\n",seed);
int num = 7;
for(int i=0;i < num;i++){
printf("%d\n",rand());
}
printf("\n\n");
srand(seed);
for(int i=0;i < num;i++){
printf("%d\n",rand());
}
printf("\n\n");
seed = seed+1;
printf("seed=%d\n",seed);
for(int i=0;i < num;i++){
printf("%d \n",rand_r(&seed));
}
return 0;
}
上一篇
下一篇
C++11 chrono 获取时间戳
C语言字符串转浮点数
C语言排序和搜索
C语言动态内存分配与释放
exit atexit 及 abort
C语言stdlib使用实例