Why is this code not generating the average correctly?

Asked

Viewed 87 times

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;

}

2 answers

3


The main problem is that the return is inside the loop, so it makes the calculation in the first step and already leaves the function then. Removing the return of loop it only runs at the end when all it was executed.

This is because the code is very disorganized. It is difficult to understand what is happening. I took the opportunity to improve this also.

I haven’t checked that 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);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

0

Try putting the return out of the keys of for, if not it leaves the function in the first interaction.

If only that doesn’t work, try to manipulate v as pointer, and not as vector. So:

S  += v + (i * sizeof(float));
  • 1

    Thank you very much!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.