Error in meter division

Asked

Viewed 39 times

1

Why is my code performing the wrong average division because of the variable contador?

int numero,contador, soma;
float media;

soma = 0;

for (contador = 1; contador <= 3; contador++) {
    printf("Digite um numero inteiro : ");
    scanf("%d",&numero);
    soma = soma + numero;   
}

media = (float)soma / contador;

printf("A media dos numeros e %.2f \n",media);
  • The way you did the variable value contador is the amount you left the loop with for ie: 4 (o is part of 1 and increments 1 while <= 3).

1 answer

1


Because you started counting at 1, in general we always start at 0, this works best to access data in a array and to make counts like this. Starting from 0 and ending when it is equal to the number you want to stop you make the code more readable and will use the right value to divide the average. So in this case when it reaches 3 it closes and does not repeat anymore, it makes request for data entry with the counter worth 0, 1 and 2, but with 3 it closes and does not. And it was exactly 3 data entered, so the split is ok.

#include <stdio.h>

int main() {
    int soma = 0;
    int contador = 0;
    for (; contador < 3; contador++) {
        printf("Digite um numero inteiro : ");
        int numero;
        scanf("%d", &numero);
        soma += numero;   
    }
    printf("A media dos numeros e %.2f \n", (float)soma / contador);
}

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

  • Thank you so much for your explanation, getting to understand where I was going wrong.

Browser other questions tagged

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