首页 > 代码库 > 随机数不是事!^~^

随机数不是事!^~^

随机数的事

总结随机数的那点事,不断总结中......


1.产生一个随机数
<span style="font-size:18px;">srand(time(0));
x=rand();//0~RAND_MAX-1
</span>

2.生成一个[a,b]之间的随机数
x=rand()%(b-a+1)+a;

3.以概率为Px%,Py%,Pz%(Px、Py、Pz均为整数且Px+Py+Pz=100)生成三个随机数
// This function generates 'x' with probability px/100, 'y' with 
// probability py/100  and 'z' with probability pz/100:
// Assumption: px + py + pz = 100 where px, py and pz lie 
// between 0 to 100 
int random(int x, int y, int z, int px, int py, int pz)
{       
        // Generate a number from 1 to 100
        int r = rand(1, 100);
      
        // r is smaller than px with probability px/100
        if (r <= px)
            return x;
 
         // r is greater than px and smaller than or equal to px+py 
         // with probability py/100 
        if (r <= (px+py))
            return y;
 
         // r is greater than px+py and smaller than or equal to 100 
         // with probability pz/100 
        else
            return z;
}