Program to calculate media

Asked

Viewed 540 times

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 me -1 for any input. would like to calculate the average sum of (n) numbers and if the user no longer wishes to move on he uses Sentinel 9999 to exit the loop and finish the program.

1 answer

2

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

To make it easier, I changed the type of the variable Average to float (it makes no sense to initialize as int) and instead of the explicit typecasting (float) I used a implicit Typecast, multiplying the teams by 1.0, which makes it a float, before the division.

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

Ah, and you have one more problem, that when Voce inserts 9999, it was being calculated together in the media, I added a check inside the while to prevent this. (must have a more elegant way, 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;
}
  • 2

    +1. But another problem is that it sums up 9999 in the average calculation. The ideal is to use one do-while or check the termination condition not to make the sum of it.

  • 1

    @Luizvieira corrected this now, but I realized the mistake. Thanks :D Great minds think alike

  • Thanks man! worked here, thanks for noticing the error in the loop too.

  • @Vitormatos if the answer solved your problem do not forget to mark it as solution, so other people can also be helped!

  • I think explicit typecasting (float) would be easier (or faster) to understand. But it’s personal preference :-)

Browser other questions tagged

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