![]() |
| | #1 |
| Registered User Join Date: Jun 2009
Posts: 31
| Random generator 0 1 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;
}
Code: 21474836470.216477 0.471353 0.312465 0.644094 0.796645 0.112260 0.999378 0.374815 0.463826 0.021919 0.175329 Thanks D. |
| Dedalus is offline | |
| | #2 |
| C++ Witch 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 | |
| | #3 |
| Registered User Join Date: Jun 2009
Posts: 31
| many thanks, I made an easy error. D. |
| Dedalus is offline | |
| | #4 |
| C++ Witch 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 | |
![]() |
| Tags |
| generator, rand(), random |
| Thread Tools | |
| Display Modes | |
|
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 |