Thursday, May 10, 2012

C code - Random Number Generator


//program to generate random numbers
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
void main()
{
   int i,n=1000;
   float r,sum=0,avg;
   time_t t;
   FILE *fp;
   clrscr();
   fp=fopen("c:\\rand.dat","w");
   srand((unsigned) time(&t)); //to randomize the seed
      for(i=0; i<n; i++)
      {
r=rand()%1000;
r=r/1000; //generates random number with 3 digits
sum+=r;
fprintf(fp,"%.3f\n",r);
       }
   avg=sum/n;
   fprintf(fp,"Average of %d random numbers= %.3f",n,avg);
fclose(fp);
   }

No comments:

Post a Comment