如何生成从0.5到1.0的随机数

如何生成从0.5到1.0的随机数。

你可以试试:

float RandomBetween(float smallNumber, float bigNumber) { float diff = bigNumber - smallNumber; return (((float) rand() / RAND_MAX) * diff) + smallNumber; } 

你应该可以使用类似的东西:

 double x = ((double)rand()) / ((double)RAND_MAX) / 2.0 + 0.5; 

除以RAND_MAX给出一个从0到1的值,将该范围除以2到0到0.5,然后加0.5给出0.5到1.(包括在低端和在顶端独占)。

像波纹管这样的东西会帮助你。

 double random(double start, double end) { double moduleValue = ((end - start) *10); //1.0 - .5 --> .5 -->> 5 double randum = rand() % moduleValue; // restrict the random to your range //if rendum == 2 --> .2 + .5 --> .7 in the range .5 -- 1.0 return (randum / 10) + start; // make your number to be in your range } 

测试代码澄清

 #include  #define RAND_NUMBER 14 #define INT_FLAG 10 int main (int argc, const char * argv[]) { // insert code here... double start = .5; double end = 1.0; double moduleValue = ((end - start) * INT_FLAG); int randum = (RAND_NUMBER / moduleValue); double result = ((double)randum/INT_FLAG) + start; printf("%f",result); printf("Hello, World!\n"); return 0; } 
 #include #include main() { int i; double b,n; srand(getpid()); n=rand()%51+50; b=n/100; printf("%f\n",b); }