Average is not calculated

4

I need to write a code that reads only 20 integer values, in the end add the positive numbers and average the negative numbers.

It usually sums the positives but when it arrives at the time of the negatives it always shows the value 0.

Here's my code:

    #include <stdio.h>
    #include <stdlib.h>

    int main()
    {
      int numerospositivos=0, soma=0, media, total=0, numero, 
      totalnegativo=0;

      float numerosnegativos=0;

      while(total<=20){
      printf("Digite um numero");
      scanf("%d",&numero);

    if(numero<0){
    numerosnegativos+=numero;
      totalnegativo++;}

      else if(numero>=0){
    numerospositivos+=numero;
    total++;}
    }

    media=numerosnegativos/totalnegativo;
    soma=numerospositivos;

      printf("A media dos numeros negativos e de:  %f",media);
      printf("A soma dos numeros positivos e:   %d",soma);

    system("PAUSE");
    return 0;
    }
    
asked by anonymous 31.08.2018 / 23:43

1 answer

3

One of the reasons for the problem is that you do not care much about organizing the code and this may sound silly, but it makes a difference even cognitive in what you are learning and doing. See that writing better makes it easier to understand why the error occurs.

Think of the problem as simply as possible.

If you want to read a specific amount of items, for is always recommended and simple. Turn to something standard to use.

If you want to add something, just go accumulating as you did. But it has an error, it is increasing the number of the read conditionally, that is, only when it reads 20 positives that the loop ends. If I had used a for I would probably avoid this problem. And note that you are using a else if where a else is enough, one is exactly the opposite condition to the other.

Only in the case of negatives you need to accumulate and count how many are because to calculate the average you need the total and how many are to make the division.

Another thing I always say is that declaring the variable closest to where it will be used makes it easier to deal with it and to know why it exists.

I've turned the total into float to give a broken number, but that's not required in the statement, so without it it should work.

#include <stdio.h>

int main() {
    int somaPositivos = 0, somaNegativos = 0, negativos = 0;
    for (int i = 0; i < 20; i++) {
        printf("\nDigite um numero");
        int numero;
        scanf("%d", &numero);
        if (numero < 0) {
            somaNegativos += numero;
            negativos++;
        } else somaPositivos += numero;
    }
    printf("A media dos numeros negativos é de:  %f\n", (float)somaNegativos / negativos);
    printf("A soma dos numeros positivos é: %d\n", somaPositivos);
}

See running on ideone . And in Coding Ground . Also put it in GitHub for future reference .

    
01.09.2018 / 00:02