2010-09-16 22 views

Respuesta

15

Usted puede tratar de:

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

Usted debe ser capaz de usar algo como:

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

La división por RAND_MAX le da un valor de 0 a 1, dividiendo dicha por dos gotas del rango de 0 a 0.5, luego agregar 0.5 le da 0.5 a 1. (inclusive en el extremo bajo y exclusivo en el extremo superior).

1

Algo así como bramido te ayudará.

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 
} 

Código de ensayo para la clarificación

#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; 
} 
+0

No es así artificialmente restringirla a intervalos de 0,1? ¿Por qué harías eso en lugar de usar el doble rango completo? – paxdiablo

+0

verifique el código de aclaración --- cuando intente dividir el .5, actuará como 1/2 en matemáticas debido a que el número generado no estará en su rango –

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); 
} 
Cuestiones relacionadas