Double rounding error even when calculating small numbers

I have this super simple code for calculating averages of given even and odd numbers, until the user gives 0. (I would use for loop but we can’t).
I’m having a really strange problem with program rounding results like 25/2 is 2.00000. Sorry if this question is stupid but I just can’t find a problem.
What am I doing completely wrong?

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

void funkcja()
{
    int sumaNiep = 0;
    int sumaPa = 0;
    int userInput = 1;
    int i = 0;

    while(userInput != 0)
    {
        //wprow zmiennej
        printf("%d. Podaj calkowita liczbe: ", i+1);
        scanf("%d", &userInput);

        //jesli parzysta
        if (userInput % 2 == 0)
        {
            sumaPa += userInput;
        } else {
            sumaNiep += userInput;
        }
        i++;
    }

    double sredniaNiep = sumaNiep/(i-1);
    double sredniaPa = sumaPa/(i-1);

    printf("\nsrednia parzysta %d / %d : %lf", sumaPa, i, sredniaPa);
    printf("\nsrednia parzysta %d / %d : %lf", sumaNiep, i, sredniaNiep);

}


int main()
{
    funkcja();
}

>Solution :

The problem is that you do an integer division at the end.

You should break out of the loop if the user enters 0 and make at least one operand a double when you do the division. You also need to count the number of evens and odds:

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

void funkcja() {
    int sumaNiep = 0;
    int sumaPa = 0;
    int userInput = 1;
    int iPa = 0;
    int iNiep = 0;
    int i = 0;

    while(1) {
        printf("%d. Podaj calkowita liczbe: ", ++i);
        if(scanf(" %d", &userInput) != 1 || userInput == 0) break; // break out

        // jesli parzysta
        if(userInput % 2 == 0) {
            sumaPa += userInput;
            ++iPa;                  // count evens
        } else {
            sumaNiep += userInput;
            ++iNiep;                // count odds
        }
    }
    if(iPa) { // avoid div by zero
        double sredniaPa = (double)sumaPa / iPa;       // double div
        printf("srednia parzysta %d / %d : %lf\n", sumaPa, iPa, sredniaPa);
    }
    if(iNiep) { // avoid div by zero
        double sredniaNiep = (double)sumaNiep / iNiep; // double div
        printf("srednia parzysta %d / %d : %lf\n", sumaNiep, iNiep, sredniaNiep);
    }
}

Leave a Reply