How can I complete the harmonic mean?

Asked

Viewed 1,482 times

0

I wonder why my code is not returning the correct values, because when I type the value it does not calculate correctly, how to enter with two notes, both valid 5.0 and 5.0, the exit should be 5.0 and this is not happening.

Use the amortized harmonic mean formula to make the program.

Follow the code below:

#include <stdio.h>

int main (void)
{
    int N, i;
    float mediaharmonica, res;

    scanf("%d", &N);
    float vetor[N];

    for (i = 0 ; i < N ; i++)
    {
        scanf("%f", &vetor[i]);
        res = 1/(vetor[i] + 1);
        mediaharmonica = N - 1 /(float)res; 
    }
    printf("%.2f", mediaharmonica);
    return 0;
}

2 answers

2

For example: media = (3 / ((1/n1) + (1 / N2) + (1 / N3))), where 3 is the total of elements, so just you accumulate the (1/n) in each iteration of for and in the end divide by the total of elements.

 #include <stdio.h>

 int main (void){
    int N, i;
    float mediaharmonica, res;
    printf("Total de elementos: "); 
    scanf("%d", &N);
    fflush(stdin);  
    float vetor[N];
    for (i = 0 ; i < N ; i++){
        printf("Elemento %i: ", i);
        scanf("%f",&vetor[i]);
        res += 1/(vetor[i]);
    }
    printf("Media: %.2f", mediaharmonica = N/res);
    return 0;
}

0

#include <stdio.h>
main() {
double a,i,s,media;
s=1;
i=0;
media=0;
while (s==1)
{
    i=i+1;
    a=0; //Condição inserida para o usuario não digitar 0.
    while (a==0) { // Laço inserido para o usuario não digitar 0.
        printf("Digite o %.0lfo valor da media harmonica: ",i);
        scanf("%lf",&a);
        if (a==0) //Condição inserida para o usuario não digitar 0.
        printf("Favor inserir valor diferente de zero\n");
    }
    media=media+(1/a);
    printf("Deseja inserir mais algum valor na media?\nDigite 1 para sim:");
    scanf("%lf",&s);
    printf("\n");
}
media=i/media;
printf("\nValor da media harmonica: %lf",media);
getchar();
}

Browser other questions tagged

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