Why is this code not generating the average correctly?

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



float media(int n, float* v){

int i;
float s;

s = 0;
for(i=0;i<n;i++){
s += v[i];
return s/n;}

}

float variancia(int n, float* v, float m){

int i;
float s;

for(i=0; i<n; i++){
s += (v[i]-m)*(v[i]-m);
return s/n;}

}

int main(){


float v[10];
float med, var;
int i;

for(i=0; i<10; i++){
printf("Digite um numero:\n");
scanf("%f", &v[i]);

}

med = media(10, v);
var = variancia(10, v, med);

printf("Media = %f Variancia = %f \n", med, var);



return 0;

}
    
asked by anonymous 13.05.2017 / 01:16

2 answers

3

The main problem is that return is inside the loop, so it does the calculation in the first step and then exits the function next. Retrieving return from loop it only runs at the end when all of it has been executed.

This is because the code is very disorganized. It is difficult to understand what is happening. I did it to improve it too.

I did not check if the calculations are correct.

#include <stdio.h>

float media(int n, float* v) {
    float s = 0;
    for (int i = 0; i < n; i++) {
        s += v[i];
    }
    return s / n;
}

float variancia(int n, float* v, float m) {
    float s = 0;
    for (int i = 0; i < n; i++) {
        s += (v[i] - m) * (v[i] - m);
    }
    return s / n;
}

int main() {
    float v[10];
    for (int i = 0; i < 10; i++) {
        printf("Digite um numero:\n");
        scanf("%f", &v[i]);
    }
    float med = media(10, v);
    float var = variancia(10, v, med);
    printf("Media = %f Variancia = %f \n", med, var);
}

See running on ideone . And at Coding Ground . Also put it on GitHub for future reference .

    
13.05.2017 / 01:31
0

Try to put return out of the keys of for , otherwise it exits the function in the first interaction.

If that alone does not work, try to manipulate v as a pointer, not as a vector. So:

S  += v + (i * sizeof(float));
    
13.05.2017 / 01:31