C Board  

Go Back   C Board > General Programming Boards > C Programming

Reply
 
LinkBack Thread Tools Display Modes
Old 06-30-2009, 08:35 AM   #1
Registered User
 
Join Date: Jun 2009
Posts: 31
Random generator 0 1

Hi

I'd like to write a random number generator between 0 and1.
I'm doing like that:

Code:
#include<stdio.h>
#include <stdlib.h>
#include <time.h>

int main(){
int b;
float r;

srand(time(NULL));

printf("%d",RAND_MAX);

for (b=11;b>0;b--){

        r=rand();

        printf("%f\n", r/RAND_MAX);

        }
return 0;
}
but i get this output:

Code:
21474836470.216477
0.471353
0.312465
0.644094
0.796645
0.112260
0.999378
0.374815
0.463826
0.021919
0.175329
why the first one is not normalized?

Thanks

D.
Dedalus is offline   Reply With Quote
Old 06-30-2009, 08:38 AM   #2
C++ Witch
 
laserlight's Avatar
 
Join Date: Oct 2003
Location: Singapore
Posts: 10,352
You printed RAND_MAX without a newline, so you confused that and the very first pseudorandom number printed. Try:
Code:
#include<stdio.h>
#include <stdlib.h>
#include <time.h>

int main(){
    int b;
    float r;

    srand(time(NULL));

    printf("%d\n", RAND_MAX);

    for (b=11;b>0;b--){
        r = rand();

        printf("%f\n", r/RAND_MAX);
    }
    return 0;
}
__________________
C + C++ Compiler: MinGW port of GCC
Build + Version Control System: SCons + Bazaar

Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
laserlight is online now   Reply With Quote
Old 06-30-2009, 08:42 AM   #3
Registered User
 
Join Date: Jun 2009
Posts: 31
many thanks, I made an easy error.

D.
Dedalus is offline   Reply With Quote
Old 06-30-2009, 08:44 AM   #4
C++ Witch
 
laserlight's Avatar
 
Join Date: Oct 2003
Location: Singapore
Posts: 10,352
By the way, the range you get is [0.0, 1.0], but [0.0, 1.0) is more commonly used, methinks. If you want the latter, you would have to say, add 1.0 to RAND_MAX in the divisor.
__________________
C + C++ Compiler: MinGW port of GCC
Build + Version Control System: SCons + Bazaar

Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
laserlight is online now   Reply With Quote
Reply

Tags
generator, rand(), random

Thread Tools
Display Modes

Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
random to int? psyadam C# Programming 7 07-22-2008 08:09 PM
Lesson #3 - Math oval C# Programming 2 04-27-2006 08:16 AM
Another brain block... Random Numbers DanFraser C# Programming 2 01-23-2005 05:51 PM
How do I restart a random number sequence. jeffski C Programming 6 05-29-2003 02:40 PM
Best way to generate a random double? The V. C Programming 3 10-16-2001 04:11 PM


All times are GMT -6. The time now is 06:23 PM.


Powered by vBulletin® Version 3.8.1
Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.3.0 RC2

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22