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

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

    This is an answer to a clarification of the question made in comment to this answer,

    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.

    The problem was to avoid 0. There are (at least) two problems with the proposed solution. One is, as the other answers indicate, that rand()+rand() can invoke undefined behavior. Best advice is to never invoke undefined behavior. Another issue is there's no guarantee that rand() won't produce 0 twice in a row.

    The following rejects zero, avoids undefined behavior, and in the vast majority of cases will be faster than two calls to rand():

    int rnum;
    for (rnum = rand(); rnum == 0; rnum = rand()) {}
    // or do rnum = rand(); while (rnum == 0);
    

提交回复
热议问题