Why does rand() + rand() produce negative numbers?

后端 未结 9 1450
没有蜡笔的小新
没有蜡笔的小新 2020-12-22 18:30

I observed that rand() library function when it is called just once within a loop, it almost always produces positive numbers.

for (i = 0; i <         


        
相关标签:
9条回答
  • 2020-12-22 19:03

    To avoid 0, try this:

    int rnumb = rand()%(INT_MAX-1)+1;
    

    You need to include limits.h.

    0 讨论(0)
  • 2020-12-22 19:07

    May be you could try rather a tricky approach by ensuring that the value returned by sum of 2 rand() never exceeds the value of RAND_MAX. A possible approach could be sum = rand()/2 + rand()/2; This would ensure that for a 16 bit compiler with RAND_MAX value of 32767 even if both rand happens to return 32767, even then (32767/2 = 16383) 16383+16383 = 32766, thus would not result in negative sum.

    0 讨论(0)
  • 2020-12-22 19:09

    rand() is defined to return an integer between 0 and RAND_MAX.

    rand() + rand()
    

    could overflow. What you observe is likely a result of undefined behaviour caused by integer overflow.

    0 讨论(0)
提交回复
热议问题