Search code examples
crandomfloating-pointdoublesrand

Precedence rules - Trouble using brackets and division with srand to get a float number


I am trying to manipulate srand so that srand returns a decimal number by division. But it's not working. My Code doesn't return a decimal number even though precedence rules should prioritize brackets before division.

#include <stdio.h>
#include <math.h>

int main(void) {

    double save;

    srand(time(NULL));

    save = (rand() % 100)/ 10;

    printf("%f", save);

    return 0;
}

However this code works fine, but I'm not happy with the solution.

#include <stdio.h>
#include <math.h>

int main(void) {

    double save;

    srand(time(NULL));

    save = rand() % 100;

    save = save / 10;

    printf("%f", save);

    return 0;
}

Can anyone explain this and give a better solution?


Solution

  • Problem of this code:

    double save;
    save = (rand() % 100) / 10;
    

    is not in precedence of operators, but because of division by integral constant 10. Try:

    save = (rand() % 100) / 10.0;
    

    yet in case you want to generate numbers from interval <0; 10) it would better to do:

    save = ((double)rand() / ((double)RAND_MAX + 1.0)) * 10.0;
    

    which will yield more precise results that will also be more uniformly distributed :)