思想:
用RANDOM(0,1)生成随机的k = b-a+1位2进制随机数,即:value = n1,n2,n3,...nk.
那么,其值等于:value = n1*2^0+n2*2^1+....nk*2^k.
分析知道,value的值在0到2^k-1之间,那么我们做这样的设计,把0到2*k-1等分为k分,分别对应到a,a+1,...,b-a+1。
得到的随机数value落在k分的哪段就是a,a+1,...,b-a+1的哪个值。
代码如下:
1 #include <iostream> 2 #include <time.h> 3 using namespace std; 4 5 int get01rand(); 6 int getabrand(int a,int b); 7 int value[100]; 8 9 void main(){ 10 srand((unsigned int)(time(NULL))); 11 int a,b; 12 cin >>a >> b; 13 cout << getabrand(a,b); 14 } 15 16 int get01rand(){ 17 return rand()%2;//(取值是K,那么生成的随机数就是0 ~ K-1) 18 } 19 20 int getabrand(int a,int b){ 21 22 int k = b - a + 1; 23 24 // 用get01rand函数生成对应k位2进制数,其值一定在0 ~ 2^k-1之间, 25 // 然后把其均分为k等分,分别对应到a,a+1,...,b. 26 int he = 0; 27 int lo = 1; 28 29 for(int p = 0;p<k;p++) // 得到k位2进制数 30 lo = lo*2; 31 int max = lo; 32 33 for(int i=0;i<k;i++) 34 { 35 if(get01rand() !=0){ //计算随机生成的数 36 lo = 1; 37 for(int j=0;j<i;j++) 38 lo=lo*2; 39 he = he + lo; 40 } 41 } 42 int deng = max/k; 43 if(he/k > deng) //如果不在对应的分段范围内,则重新分配 44 getabrand(a,b); 45 46 return he/deng+a; //否则,返回对应分段的 b - a + 1的值 47 }