Problem with a counter adding numbers inserted in C

Asked

Viewed 39 times

-3

I have to read 6 values and then show how many of these typed values were positive. On the next line, you should show the average of all positive values typed, with one digit after the decimal point.

The code is meeting all the requirements of the question, however it is not returning the average of all positive values typed and I’m not understanding the reason.

Code:

#include <stdio.h>

int main() {
    int counterNumPositivos, soma, counterEntradas;
    double numDigitado, media;
    soma = 0;
    counterNumPositivos = 0;
    counterEntradas = 0;
  
    while (counterEntradas <6){
       scanf("%lf", &numDigitado);
       counterEntradas += 1;
       soma += numDigitado;
       if (numDigitado >= 0)
           counterNumPositivos += 1;

}      
    media = soma / 6;
      
    printf("%d valores positivos\n", counterNumPositivos);
    printf("%.1f\n", media);

    return 0;
}

I’m racking my brain with something that I believe is simple haha.

1 answer

0


Where is the problem?

Your code has 2 problems:

  1. Is adding to the sum values that are also negative or zero.
  2. Is dividing the sum by 6 and not by all positive numbers.

How to solve?

Put the sum part inside the if, this way you are only adding up the ones that are positive. In the end, divide by the amount of positive and code will work as expected:

while (counterEntradas <6){
    scanf("%lf", &numDigitado);
    counterEntradas += 1;
    if (numDigitado >= 0) {
        soma += numDigitado;
        counterNumPositivos += 1;
    }
}

media = soma / counterNumPositivos;
  • 1

    Corrected here. Thanks for the remark!

  • If I’ve solved your question, don’t forget to mark it as a response in the green tick. This makes more people with the same doubt that you can easily find the solution to the problem.

Browser other questions tagged

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