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

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

    Basically rand() produce numbers between 0 and RAND_MAX, and 2 RAND_MAX > INT_MAX in your case.

    You can modulus with the max value of your data-type to prevent overflow. This ofcourse will disrupt the distribution of the random numbers, but rand is just a way to get quick random numbers.

    #include 
    #include 
    
    int main(void)
    {
        int i=0;
    
        for (i=0; i<100; i++)
            printf(" %d : %d \n", rand(), ((rand() % (INT_MAX/2))+(rand() % (INT_MAX/2))));
    
        for (i=0; i<100; i++)
            printf(" %d : %ld \n", rand(), ((rand() % (LONG_MAX/2))+(rand() % (LONG_MAX/2))));
    
        return 0;
    }
    

提交回复
热议问题