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

时间:2010-09-16 07:24:29

标签: c

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

4 个答案:

答案 0 :(得分:15)

您可以尝试:

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

答案 1 :(得分:5)

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

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

RAND_MAX的除法给出一个从0到1的值,将该范围除以2到0到0.5,然后加0.5得到0.5到1.(包括在低端并且在最高端)。

答案 2 :(得分: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 <stdio.h>
#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;
}

答案 3 :(得分:0)

#include<stdio.h>
#include<stdlib.h>
main()
{
int i;
double b,n;
srand(getpid());

n=rand()%51+50;
b=n/100;

printf("%f\n",b);
}