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

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

    thx. 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

    It sounds like an XY problem to me, in which in order to not get a 0 from rand(), you call rand() two times, doing the program slower, with a new setback and the possibility of getting a 0 is still there.

    Another solution is using uniform_int_distribution, which creates a random and uniformly distributed number in the defined interval:

    https://wandbox.org/permlink/QKIHG4ghwJf1b7ZN

    #include 
    #include 
    #include 
     
    int main()
    {
        const int MAX_VALUE=50;
        const int MIN_VALUE=1;
        std::random_device rd;
        std::mt19937 gen(rd());
        std::uniform_int_distribution<> distrib(MIN_VALUE, MAX_VALUE);
        std::array weight={0};
    
        for(int i=0; i<50000; i++) {
            weight[distrib(gen)-MIN_VALUE]++;
        }
        
        for(int i=0;i<(int)weight.size();i++) {
            std::cout << "value: " << MIN_VALUE+i << " times: " << weight[i] << std::endl; 
        }
    }
    

提交回复
热议问题