Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
Hi, im having difficulty with the random number generator in C, rand(). What Im trying to do is estimate the mean of a real number generator. So I need the random function to throw up a real number between 0 & 1. I know I have to make it into a float but when i do this i get the same number thrown up all the time or 2 or 3 very similar numbers.
I havnt managed to get the random numbers to be between 0 and 1 either yet.
Here is the code im using at the moment
#include <stdio.h>
#include <stdlib.h>int main(void)
{
int i;
randomize();
for (i=0; i<10; i++)
printf ("\n%d", (float)rand()/10);getchar();
getchar();}
Thanks for any help or suggestions, im sure the answer is really simple but i just cant see the wood for the trees.

What compiler are you using? rand() can be different between compilers.
One problem is that you are printing a float with a %d instead of a %f.
I assume that your rand() returns an int. Then you cast it to float. Then you divide by an int 10, but the compiler will convert the int 10 to float 10 before doing the division. The result of the division will also be a float, which will be printed by printf() using the %d. The %d should be a %f.

You could use a very basic form of rand along with srand.
#include <time.h>
...
srand((unsigned)time(NULL));
my_num = rand() % some_value + some_offset;
...

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |