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

后端 未结 9 1470
没有蜡笔的小新
没有蜡笔的小新 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 18:53

    the reason i was adding was to avoid '0' as the random number in my code. rand()+rand() was the quick dirty solution which readily came to my mind.

    A simple solution (okay, call it a "Hack") which never produces a zero result and will never overflow is:

    x=(rand()/2)+1    // using divide  -or-
    x=(rand()>>1)+1   // using shift which may be faster
                      // compiler optimization may use shift in both cases
    

    This will limit your maximum value, but if you don't care about that, then this should work fine for you.

提交回复
热议问题