How to generate a random int in C?

后端 未结 27 2093
故里飘歌
故里飘歌 2020-11-22 00:31

Is there a function to generate a random int number in C? Or will I have to use a third party library?

27条回答
  •  不知归路
    2020-11-22 00:42

    Hearing a good explanation of why using rand() to produce uniformly distributed random numbers in a given range is a bad idea, I decided to take a look at how skewed the output actually is. My test case was fair dice throwing. Here's the C code:

    #include 
    #include 
    #include 
    
    int main(int argc, char *argv[])
    {
        int i;
        int dice[6];
    
        for (i = 0; i < 6; i++) 
          dice[i] = 0;
        srand(time(NULL));
    
        const int TOTAL = 10000000;
        for (i = 0; i < TOTAL; i++)
          dice[(rand() % 6)] += 1;
    
        double pers = 0.0, tpers = 0.0;
        for (i = 0; i < 6; i++) {
          pers = (dice[i] * 100.0) / TOTAL;
          printf("\t%1d  %5.2f%%\n", dice[i], pers);
          tpers += pers;
        }
        printf("\ttotal:  %6.2f%%\n", tpers);
    }
    

    and here's its output:

     $ gcc -o t3 t3.c
     $ ./t3 
            1666598  16.67%     
            1668630  16.69%
            1667682  16.68%
            1666049  16.66%
            1665948  16.66%
            1665093  16.65%
            total:  100.00%
     $ ./t3     
            1667634  16.68%
            1665914  16.66%
            1665542  16.66%
            1667828  16.68%
            1663649  16.64%
            1669433  16.69%
            total:  100.00%
    

    I don't know how uniform you need your random numbers to be, but the above appears uniform enough for most needs.

    Edit: it would be a good idea to initialize the PRNG with something better than time(NULL).

提交回复
热议问题