本文翻译自:Why does rand() + rand() produce negative numbers?
I observed that rand()
library function when it is called just once within a loop, it almost always produces positive numbers. 我观察到rand()
库函数在循环中只调用一次,它几乎总是产生正数。
for (i = 0; i < 100; i++) {
printf("%d\n", rand());
}
But when I add two rand()
calls, the numbers generated now have more negative numbers. 但是当我添加两个rand()
调用时,现在生成的数字会有更多的负数。
for (i = 0; i < 100; i++) {
printf("%d = %d\n", rand(), (rand() + rand()));
}
Can someone explain why I am seeing negative numbers in the second case? 有人可以解释为什么我在第二种情况下看到负数吗?
PS: I initialize the seed before the loop as srand(time(NULL))
. PS:我在循环之前将种子初始化为srand(time(NULL))
。
#1楼
参考:https://stackoom.com/question/25K3S/为什么rand-rand-产生负数
#2楼
rand()
is defined to return an integer between 0
and RAND_MAX
. rand()
定义为返回0
到RAND_MAX
之间的整数。
rand() + rand()
could overflow. 可能会溢出 What you observe is likely a result of undefined behaviour caused by integer overflow. 您观察到的可能是整数溢出导致的未定义行为的结果。
#3楼
The problem is the addition. 问题是增加。 rand()
returns an int
value of 0...RAND_MAX
. rand()
返回一个int<