The function rand()
of the standard library stdlib.h
generates only pseudo-random numbers whole amid 0
and RAND_MAX
.
A generic solution would be to implement a function capable of generating floating point values between 0
and 1
, look at you:
double randf( void )
{
return rand() / ((double)RAND_MAX);
}
Another valid solution would be to use a function capable of generating random numbers between 0
and a predetermined maximum value:
double randf( double max )
{
return rand() / ( RAND_MAX / max );
}
And finally, a function capable of generating floating point numbers within a pre-established range:
double randf( double min, double max )
{
return min + ( rand() / ( RAND_MAX / ( max - min ) ) );
}
Testing:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
double randf( double min, double max )
{
return min + ( rand() / ( RAND_MAX / ( max - min ) ) );
}
int main()
{
int i = 0;
/* Inicializa gerador de numeros aleatorios usando o horario
* do sistema como semente */
srand(time(NULL));
/* Gera e exibe 10 numeros aleatorios entre 1.5 e 1.9 */
for( i = 0; i < 10; i++ )
printf( "%g\n", randf( 1.5, 1.9 ) );
return 0;
}
Possible Exit:
1.52526
1.777
1.77164
1.83923
1.58224
1.60071
1.88104
1.64621
1.78467
1.77367
this answer would help you? https://answall.com/a/128469/110782
– Luiz Augusto
Possible duplicate of Rand between numbers with comma
– Vinicius Fernandes
@Vinicius, helped a lot, thanks!
– user148289
@Luiz, it worked, thanks anyway!
– user148289