How can I complete the harmonic average?

0

I would like to know why my code is not returning the correct values, because when I type the value it does not calculate correctly, like entering two notes, both being and 5.0 , the output should be 5.0 and this is not happening.

Use the amortized mean harmonic formula to make the program.

The following is 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;
}
    
asked by anonymous 02.05.2015 / 03:05

2 answers

2
For example, media = (3 / (1 / n1) + (1 / n2) + (1 / n3)) 3 is the total of elements, so you only have to accumulate the (1 / n) in each iteration of for and in the end divide by the total 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;
}
    
02.05.2015 / 03:23
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();
}
    
03.02.2016 / 10:50