Computing.Net > Forums > Programming > Random Number Generator in C

Computer Problems? Computing.Net has over 1,000,000 posts about all things technology related! Over 90% answered within 24 hours! Click here to start participating now! Also, be sure to check out the New User Guide.

Random Number Generator in C

Reply to Message Icon

Name: Krysko
Date: February 17, 2004 at 06:31:16 Pacific
OS: Windoze
CPU/Ram: ?
Comment:

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.



Sponsored Link
Ads by Google

Response Number 1
Name: Don Arnett
Date: February 17, 2004 at 08:47:13 Pacific
Reply:

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.



0

Response Number 2
Name: Ronin1
Date: February 17, 2004 at 16:05:46 Pacific
Reply:

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;
...


0

Sponsored Link
Ads by Google
Reply to Message Icon

Related Posts

See More







Post Locked

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


Go to Programming Forum Home


Sponsored links

Ads by Google


Results for: Random Number Generator in C

Random number generator www.computing.net/answers/programming/random-number-generator/12990.html

Random Number Gen. In C www.computing.net/answers/programming/random-number-gen-in-c/12219.html

Randomizing numbers www.computing.net/answers/programming/randomizing-numbers/141.html