Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I receive this error when generating a random float?

Tags:

c

random

Trying to generate a psuedo-random float btwn 0 and 1. Getting this error when I run the code:

‘RAND_MAX’ undeclared (first use in this function)

#include <stdio.h>
#include <time.h>

int main(test, numpoints, numtrials, dimension){

    //generate a random number
    srand(time(NULL));
    float r = (float)(rand()/RAND_MAX +1);


    printf("%.6f", r);
    printf("\n");
}
like image 644
hannah Avatar asked Jun 16 '26 05:06

hannah


1 Answers

  1. To use RAND_MAX in C, you need to include its header:

    #include <stdlib.h>
    
  2. rand()/RAND_MAX is an integer division, if you want floating division, you should covert it to float first, then divide: (float)(rand()) / RAND_MAX

  3. You need to define your main as:

    int main ( int arc, char **argv )
    
like image 126
herohuyongtao Avatar answered Jun 20 '26 10:06

herohuyongtao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!