2

Why is rand_float only returning the value 0.000000?

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

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

    //generate a random number
    float r = rand_float();

    //print it
    printf("%f", r);
    printf("\n");
}

//function generates a random float in [0,1]
int rand_float(){
    srand(time(NULL));
    return (float)rand()/RAND_MAX;
}
hannah
  • 889
  • 4
  • 13
  • 27
  • 1
    because you're returning an **int** from `int rand_float()` – phuclv Mar 05 '14 at 04:28
  • 1
    also, [main](http://stackoverflow.com/questions/4176326/arguments-to-main-in-c) was not defined like that, you cannot use arbitrary parameters – phuclv Mar 05 '14 at 04:32

1 Answers1

4

Note the return type of rand_float is int.

So the [0,1) value (in the float) is being implicitly cast to 0 (an int), which is all that function will ever return.

Fix the return type - by changing it from int to float.

Also, either forward-declare the rand_float function or move the function definition ahead of the main function .. and check out the other comments on your main question. Enable (and read) compiler warnings for hints about [potentially] problematic code!

user2864740
  • 60,010
  • 15
  • 145
  • 220
  • Not sure I understand. Can I declare a function with float instead of int, as in float rand_float(){...} ? – hannah Mar 05 '14 at 04:26
  • @hannah Yes, you can .. *but* you should forward-declare the function (either with a declaration or moving the definition). In this case, just move the `rand_float` function definition *above* `main`. – user2864740 Mar 05 '14 at 04:28
  • why not? a function can return anything – phuclv Mar 05 '14 at 04:29
  • 2
    Also, take `srand()` outside the function and put it in `main()` where it belongs or your numbers won't be random even after you fix the float problem. – Lee Daniel Crocker Mar 05 '14 at 06:42