Incorrect Print Values

0

I do not know where I'm going wrong and are printing incorrect media values.

#include <stdio.h>

int main (){
int i, num, soma, maior, menor;
float media;

printf ("Informe 10 valores:\n");
for (i=1; i<=10; i++){
    scanf ("%d", &num);
    if (i==0){
        maior=num;
        menor=num;
    }
    else{
        if (num > maior){
            maior=num;
        }
        if (num < menor){
            menor=num;
        }
}
soma = soma + num;
media = soma / 10;
}
printf ("Media: %.2f", media);
printf ("\nMaior: %d", maior);
printf ("\nMenor: %d", menor);
}
    
asked by anonymous 23.10.2017 / 20:05

2 answers

2

Below is the code with some corrections.

#include <stdio.h>

    int main (){
    int i, num, soma, maior, menor;
    float media;

    printf ("Informe 10 valores:\n");
    soma=0;//Faltava inicializar a variável soma, estava com valor "lixo" da memória
    for (i=0; i<10; i++)//inicializei em 0, com i=1 ele não estava tratando todos os valores de num
    {
        scanf ("%d", &num);
        if (i==0){
            maior=num;
            menor=num;
        }
        else{
            if (num > maior){
                maior=num;
            }
            if (num < menor){
                menor=num;
            }
    }
    soma = soma + num;//Somatório de todos os 10 valores
    }
    media = soma / 10.0;//Soma dividido por 10.0, divisão de int por float resulta em float
    printf ("Media: %.2f", media);
    printf ("\nMaior: %d", maior);
    printf ("\nMenor: %d", menor);
    }

I ran the test with values from 1 to 10 and got the following output:

    Media: 5.50
    Maior: 10
    Menor: 1
    
23.10.2017 / 21:05
4

There are several errors, probably a mixture of conventions that you have not noticed:

  • i is never zero, so it never starts the values of menor nor maior
  • The value of soma is not initialized, so it loads memory junk
  • Calculating media is being done with integer arithmetic
  • You do not need to calculate the average at each iteration
  • Solving Problems

    The first one is iterating starting at 0 and going up to 10 at the open interval. That is:

    for (i = 0; i < 10; i++) ...
    

    Simply declaring the soma variable already initialized solves the problem:

    int i, num, soma = 0, maior, menor;
    

    Withdraw average calculation from the middle of the iteration, but keeping the calculation of soma resolves item 4.

    When you finish the iteration, dividing by 10 as a floating point solves item 3:

    media = soma / 10.0f
    
        
    23.10.2017 / 20:12