Question

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?

Was it helpful?

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 :)

OTHER TIPS

It has no relation with Operator precedence!
rand() returns int type and dividing it by an integer will also return int value. You have to cast (rand() % 100)/ 10 to double

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

In second case

save = rand() % 100;

promotes value obtained by rand() % 100 to double. And then dividing save by 10 is giving you right answer, i,e, double.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top