c - Why does rand() + rand() produce negative numbers? -
i observed rand()
library function when called once within loop, produces positive numbers.
for (i = 0; < 100; i++) { printf("%d\n", rand()); }
but when add 2 rand()
calls, numbers generated have more negative numbers.
for (i = 0; < 100; i++) { printf("%d = %d\n", rand(), (rand() + rand())); }
can explain why seeing negative numbers in second case?
ps: initialize seed before loop srand(time(null))
.
rand()
defined return integer between 0
, rand_max
.
rand() + rand()
could overflow. observe result of undefined behaviour caused integer overflow.
Comments
Post a Comment