I wrote this code in C that prints a random value (float) between 0 and 1 inclusively. The code compiles and works.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
float main()
{
srand(time(NULL));
float float_rand = rand() / (float) RAND_MAX; /* [0, 1.0] */
printf("%.2lf\n", float_rand);
return 0;
}
Now I've tried to incorporate that code into a program that asks you for a number n and creates an array of length n with random values (floats) between 0 and 1 inclusively, and prints the average of those values. This is the code I have. It compiles, but it's not giving me the right results. What am I doing wrong? I'm kind of a newbie to C and Stackoverflow too. This is my first question. Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
float main()
{
int i;
int n;
printf("Choose a number n: ");
scanf("%d", &n);
float array[n];
srand(time(NULL));
for (i = 0; i < n; i++) {
array[i] = rand() / (float) RAND_MAX; /* [0, 1.0] */
}
float sum = 0;
for (i = 0; i < n; i++) {
sum += array[i];
printf("%.2lf\n", sum / n);
return 0;
}
}
Any help will be greatly appreciated. This is not a homework assignment, just something I've been trying to do for a while, as an exercise. I've written functional code that does this in Python, in R, and in GNU Octave. I just wanted to reproduce it in C.
Aucun commentaire:
Enregistrer un commentaire