Printing random decimal numbers in a text file
Hi,
I am trying to create a simple program that can generate numbers in a separate .txt file.
The random numbers generated should be:
1. normalised (if i am not mistaken, it should be divided by 32767) to be within the range of -1.000000 to 1.000000
2. up to 6 decimal places
However I encountered a couple of problems:
1. The random numbers I generate are whole numbers (when what I want are random numbers up to 6 decimal places)
2. When I try to normalise the numbers (i.e. divide it by 32767), all my numbers become 0.00000
Here is the program:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <time.h>
double main()
{
double i;
FILE *file;
file = fopen("numbers.txt", "w");
if(file==NULL) {
printf("An error has occurred.\n");
return 1;
}
srand(time(NULL));
for(i=0 ; i<1000 ; i++) /* 1000 random numbers to be generated*/
{
double random;
random = (rand()%32767+1)/32767;
fprintf(file, "%lf\n", random);
}
fclose(file);
return 0;
}
Hope someone would be able to help!
Thanks!
Re: Printing random decimal numbers in a text file
Yeah. you made mistake in calculation.
random = (rand()%32767+1)/32767;
It takes 32767 values integer and this (rand()%32767+1) value as float. so it returns 0.000000
Change the calculation like this it will work.
Code:
random = (rand()%32767+1)/32767.0f;
Now, it will take both values are float. so it will generate random numbers.
Re: Printing random decimal numbers in a text file
Thanks it works!
I have another problem:
I would like to now print these numbers in an array (with a 'tab' spacing in between the numbers). Any suggestions in editing the code?
I should look something like (in the text file):
0.123456 0.234567 0.345678
0.789456 0.456232 0.756159
... ...