problem with rand()

P

pereges

I wrote the following program to generate a seuence of uniformly
distributed random points between 0 and 1. It is giving only zeros as
output.
#include <stdio.h>
#include <stdlib.h>

int main(void)
{

int i;
int a;
for(i=0;i<10;i++)
{
a =((double)rand())/(RAND_MAX+1) ;
printf("%f", a);
}
return 0;
}
 
J

Joachim Schmitz

pereges said:
I wrote the following program to generate a seuence of uniformly
distributed random points between 0 and 1. It is giving only zeros as
output.
#include <stdio.h>
#include <stdlib.h>

int main(void)
{

int i;
int a;
double a;
for(i=0;i<10;i++)
{
a =((double)rand())/(RAND_MAX+1) ;
printf("%f", a);
}
return 0;
}

Bye, Jojo
 
L

Lew Pitcher

pereges said:
I wrote the following program to generate a seuence of uniformly
distributed random points between 0 and 1. It is giving only zeros as
output.
#include <stdio.h>
#include <stdlib.h>

int main(void)
{

int i;
int a;
NB: ---^
for(i=0;i<10;i++)
{
a =((double)rand())/(RAND_MAX+1) ;

Questions for the student:
1) What value of rand() will cause a to equal 1?
2) How likely would it be for rand() to return the value that would
cause a to compute out to 1?
3) What will a be set to for all other values returned by rand()?
printf("%f", a);
}
return 0;
}

--
Lew Pitcher

Master Codewright & JOAT-in-training | Registered Linux User #112576
http://pitcher.digitalfreehold.ca/ | GPG public key available by request
---------- Slackware - Because I know what I'm doing. ------
 
P

pereges

pereges said:




You didn't mean int a, but double a

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
int i = 0;
while(i++ < 10)
{
double a = rand() / (RAND_MAX + 1.0);
printf("%f\n", a);
}
return 0;

}

Now see if you can work out why you get the same results on every run. (The
FAQ has something to say about this.)

--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
 
J

Jack.Thomson.v3

I wrote the following program to generate a seuence of uniformly
distributed random points between 0 and 1. It is giving only zeros as
output.
#include <stdio.h>
#include <stdlib.h>

int main(void)
{

int i;
int a;
for(i=0;i<10;i++)
{
a =((double)rand())/(RAND_MAX+1) ;
printf("%f", a);
}
return 0;}


#include <stdio.h>
#include <stdlib.h>

int main(void)
{

int i;
double a; // Here is the modification

for(i=0;i<10;i++)
{
a =((double)rand())/(RAND_MAX+1) ;
printf("%f", a);
}
return 0;
}


~Jack
http://programmingsite.googlepages.com
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,072
Latest member
trafficcone

Latest Threads

Top