odd thing

Started by
2 comments, last by Fruny 18 years, 10 months ago
these not work correctly. float d = rand()/RAND_MAX; but int r = rand(); float d = r/RAND_MAX; these work but float r = rand(); float d = r/RAND_MAX; float d =rand()/0x7fff; why where is the problem?
Advertisement
I am not for sure but i think it is because you are declaring float d two times.

float d = rand()/RAND_MAX;

but int r = rand();
float d = r/RAND_MAX;

I am not well up with rand() but there you have float d = rand()/RAND_MAX and a second that has the same name so the compiler won't know which is which. You need to rename the other float so that it will work [smile].

Edit: also why would you want to assigne two randum number generators together?
That's two different snippets (both doing the same thing, but the second is spread out).

I believe that it's not working because your number is getting rounded (since it has an int in it). If you convert to a float or use a float to begin with, it should work fine:
int r = rand();float d = (float)r/RAND_MAX;//orfloat r = rand();float d = r/RAND_MAX;// orfloat d = (float)rand()/RAND_MAX;
rand()/RAND_MAX

Both terms are integers, thus the compiler generates an integer division. Given that RAND_MAX is always larger than rand(), the result is always integer zero, which then gets converted to a float. You need to explicitely convert one of the terms to a floating-point value to cause a floating-point division to be generated.

rand() / (float)RAND_MAX
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan

This topic is closed to new replies.

Advertisement