Average is not calculated

Asked

Viewed 105 times

5

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

It normally adds up the positives but when it arrives at the time of the negatives it always shows the value 0.

Here is 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;
    }

1 answer

3


One of the reasons for the problem is that you don’t care much for organizing the code, and it may sound silly, but it makes even a cognitive difference in what you’re learning and doing. Note 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 the for is always more recommended and simple. Turns to something standard to use.

If you want to add something up, just pile it up like you did. But there is an error, is increasing the number of read conditionally, IE, only when read 20 positive that the loop closes. If you’d used one for probably avoid this problem. And note that you are using a else if where a else Enough is enough, one is a condition exactly contrary to the other.

Only in the case of negatives need to accumulate and count how much they are because to calculate the precise average of the total and how many are to divide.

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

I turned the total into float to give a broken number, but this is not requirement placed in the statement, so without 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);
}

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

Browser other questions tagged

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