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. 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.– Luiz Vieira
@Luizvieira corrected this now, but I realized the mistake. Thanks :D Great minds think alike
– leofontes
Thanks man! worked here, thanks for noticing the error in the loop too.
– Vitor Matos
@Vitormatos if the answer solved your problem do not forget to mark it as solution, so other people can also be helped!
– JuniorNunes
I think explicit typecasting (float) would be easier (or faster) to understand. But it’s personal preference :-)
– Daniel Grillo