Program to calculate media

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

int main()
{
    int sum = 0;
    int times = 0;

    int number;
    int average;

    while ( number != 9999 ){

        printf( " Type the number and i will make the average, 9999 to end:\n ");
        scanf("%d", &number);
        times = times + 1;
        sum = number + sum;
    }
    average = (float)sum/times;
    printf("The average is %f", average);
    return 0;
}

When I run this program, average is returning -1 for any input. I would like to calculate the average of the sum of (n) numbers and if the user does not want to move on he uses Sentinel 9999 to exit the loop and end the program.

    
asked by anonymous 07.12.2016 / 02:29

1 answer

2

I tested here, what was happening is that your average variable was initialized as int, so afterwards you were trying to put a float in an int variable.

To facilitate, I changed the variable type to float (it does not make sense to initialize as int) and instead of explicit typecasting (float) I used an implicit typecast, multiplying the times by 1.0, which makes it a float , before the division.

Here it worked, test there and any questions I try to explain better what was happening, but I think it is a very small error.

Oh, and you have one more problem, that when you enter 9999, it was being calculated together in the media, I added a check inside the while to prevent this. (should have a more elegant, but I made it simple just to leave the correct answer)

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

int main()
{
    int sum = 0;
    int times = 0;

    int number;
    float average;

    while ( number != 9999 ){

        printf( " Type the number and i will make the average, 9999 to end:\n ");
        scanf("%d", &number);
        if(number != 9999) {
            times = times + 1;
            sum = number + sum;
        }
    }
    average =  sum/ (times * 1.0);
    printf("The average is %f", average);
    return 0;
}
    
07.12.2016 / 02:43