rand()函数

石乐志123333 2012-07-02 08:34:53
求大神用简洁明了的语言讲一下rand()函数和srand()函数的用法,区别什么的
勿百度
百度上的太长太复杂,完全看不懂啊,什么种子
...全文
146 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
薛定谔之死猫 2012-07-02
  • 打赏
  • 举报
回复
srand写成了sand,修改下就好,个数可以自己随意追加~
cxdzxc 2012-07-02
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 的回复:]

比如你调用顺序
C/C++ code
sand(1);
printf("%d\n",rand());
printf("%d\n",rand());

和C/C++ code
sand(1);
printf("%d\n",rand());
printf("%d\n",rand());
会返回相同的随机数序列
C/C++ code
sand(1);
printf("%d\n",rand(……
[/Quote]
这是说明问题的好方法
薛定谔之死猫 2012-07-02
  • 打赏
  • 举报
回复
纠正下rand的返回值是0到宏RAND_MAX的值之间,有些语言返回浮点的值是0到1之间,右面可以乘以一些数进行转换,32位主机的RAND_MAX宏一般定义为32767
薛定谔之死猫 2012-07-02
  • 打赏
  • 举报
回复
比如你调用顺序
sand(1);
printf("%d\n",rand());
printf("%d\n",rand());

sand(1);
printf("%d\n",rand());
printf("%d\n",rand());
会返回相同的随机数序列
sand(1);
printf("%d\n",rand());
printf("%d\n",rand());

sand(2);
printf("%d\n",rand());
printf("%d\n",rand());
就不一样了

qq120848369 2012-07-02
  • 打赏
  • 举报
回复
NAME
rand, rand_r, srand - pseudo-random number generator

SYNOPSIS
#include <stdlib.h>

int rand(void);

int rand_r(unsigned int *seedp);

void srand(unsigned int seed);

Feature Test Macro Requirements for glibc (see feature_test_macros(7)):

rand_r(): _POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _POSIX_SOURCE

DESCRIPTION
The rand() function returns a pseudo-random integer in the range 0 to RAND_MAX inclusive (i.e., the mathematical range [0, RAND_MAX]).

The srand() function sets its argument as the seed for a new sequence of pseudo-random integers to be returned by rand(). These sequences are repeat-
able by calling srand() with the same seed value.

If no seed value is provided, the rand() function is automatically seeded with a value of 1.

The function rand() is not reentrant or thread-safe, since it uses hidden state that is modified on each call. This might just be the seed value to be
used by the next call, or it might be something more elaborate. In order to get reproducible behavior in a threaded application, this state must be
made explicit; this can be done using the reentrant function rand_r().
薛定谔之死猫 2012-07-02
  • 打赏
  • 举报
回复
rand是用来产生伪随机数序列的,srand是用来设置伪随机数种子的,是为后继的rand调用服务的,相同的种子将生产相同的伪随机数序列,所以一般用当前时间来设置伪随机数种子,这样可以有效防止随机数序列重复,rand返回0到预定义的最大随机数值,一般地是0到1之间,你通过rand的返回乘以一个大数得到符合自己需要的伪随机数,rand是不可重入的,也就说不是线程安全的,操作系统一般会提供可重入的版本供你选用~

69,370

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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