3

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?

dcaswell
  • 3,137
  • 2
  • 26
  • 25

2 Answers2

4

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

LihO
  • 41,190
  • 11
  • 99
  • 167
  • Thank you! that explains alot! but... could u explain why `save = ((double)rand() / ((double)RAND_MAX + 1.0)) * 9.9;` is better than for instance `save = ((double)rand() / ((double)RAND_MAX)) * 10;` – user2874149 Oct 12 '13 at 15:08
  • That is if im looking for a number that is, 0 <= number <=10, not 0 < number < 10, – user2874149 Oct 12 '13 at 15:22
  • @EricPostpischil: What makes you think that scaling down using `RAND_MAX + 1.0` produces less uniform distribution than `%` ? – LihO Oct 12 '13 at 17:57
  • @EricPostpischil: Ah, yah. You're right with that multiplication with `9.9`, it should be `10.0` indeed. – LihO Oct 12 '13 at 18:35
0

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.

haccks
  • 104,019
  • 25
  • 176
  • 264