关于 rand() 函数返回值的值域的疑问

businessmaning 2013-09-17 11:25:11
《C语言参考手册》中关于 rand() 函数有如下描述。



(1)rand() 函数的原型

int rand(void);

(2)连续调用 rand 将返回 0 到 int 类型的最大可表示的正值(含该值)之间的整数值,它们是一个伪随机数生成器所产生的连续结果。在标准 C 中,rand 的上界是上 RAND_MAX 所指定的,这个值至少是 32 767。

问题:rand 返回的值包括 0 吗?一直以来都有这个疑问,也做了一些简单的实验,结果是不包括 0,但毕竟没有找到文字说不包括 0,所以一直不能肯定。虽然从 (2) 的描述来看,应该是不包括 0 的。所以还是决定向大家咨询一下,rand 返回的值域到底是 (0, RAND_MAX],还是 [0, RAND_MAX]。期待您的回答。
...全文
285 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
yulinlang 2013-09-18
  • 打赏
  • 举报
回复
http://en.cppreference.com/w/cpp/numeric/random/rand std::rand C++ Numerics library Pseudo-random number generation Defined in header <cstdlib> int rand(); Returns a pseudo-random integral value between ​0​ and RAND_MAX (0 and RAND_MAX included). std::srand() seeds the pseudo-random number generator used by rand(). If rand() is used before any calls to srand(), rand() behaves as if it was seeded with srand(1). Each time rand() is seeded with srand(), it must produce the same sequence of values on successive calls. Other functions in the standard library may call rand, it is implementation-defined which functions do so. It is implementation-defined whether rand() is thread-safe. Parameters (none) Return value Pseudo-random integral value between ​0​ and RAND_MAX. Notes There are no guarantees as to the quality of the random sequence produced. In the past, some implementations of rand() have had serious shortcomings in the randomness, distribution and period of the sequence produced (in one well-known example, the low-order bit simply alternated between 1 and 0 between calls). rand() is not recommended for serious random-number generation needs, like cryptography.
二零一四Tenc 2013-09-18
  • 打赏
  • 举报
回复
应该包括0,我们常常这样用rand()%x,表示产生[0,x-1]之间的随机数
max_min_ 2013-09-17
  • 打赏
  • 举报
回复
[0, RAND_MAX]
  • 打赏
  • 举报
回复
是[0, RAND_MAX]
大尾巴猫 2013-09-17
  • 打赏
  • 举报
回复
不知道。不同编译器实现可能不一样。 用的时候是 rand() % x,只要x < RAND_MAX,结果肯定有0了

69,369

社区成员

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

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