1 //产生[low,high]内的任意随机数,并返回 2 float randnum(int optimization,float low,float high) 3 { 4 int ret_rnd = 0.0; 5 6 float integerf = 0.0; 7 float driftf = 0.0; 8 9 if (low >= high) 10 { 11 printf("low >= high,rearrange them\n"); 12 getchar(); 13 return; 14 } 15 //--------------------------------------------- 16 17 int integer; //整数部分 18 int decimals; //小数部分 19 20 float diff = high - low; 21 22 integer = (int)(high - low); //取整数部分 23 24 decimals = diff - integer; //取小数部分 25 //--------------------------------------------- 26 27 //1.先计算一个整数偏量值 28 if (integer > 0) 29 30 integerf= (float)(rand() % integer); 31 32 else 33 integerf= 0.0; 34 35 //2.在整数偏量的基础上进行波动 36 do 37 { 38 driftf = (float)(rand() / RAND_MAX);//产生小数 39 40 driftf *= (rand() % 2 == 0 ? 1 : -1); 41 42 } while ((integerf+driftf<0)||(integerf+driftf>diff)); 43 44 45 46 ret_rnd = low+(integerf + driftf) ; 47 48 return ret_rnd; 49 50 51 }
时间: 2024-10-11 23:57:49