changing probability of getting a random number

前端 未结 7 1550
南方客
南方客 2020-12-09 22:15

I would like to generate a random number between 0 and 3 and I have the following in my code:

int random = rand() % 4;

This works fine but

7条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-09 22:48

    Just code exactly what you want:

    int myrand(void)
    {
        const int percentZero = 10;
        if ((rand()%100) < percentZero) return 0;
        return 1 + (rand() % 3);
    }
    

    You can change the percentage of time zero is returned to whatever you want.

提交回复
热议问题