Reputation:
#include <stdio.h>
#include <stdlib.h>
int main() {
int Sum=0,numbers;
double Average;
int counter = 0;
printf("\nPlease Enter the Numbers one by one\n");
for(;;) {
scanf("%d",&numbers);
if(numbers == 0) {
break;
}
else {
Sum = Sum + numbers;
counter++;
}
}
Average = Sum/counter;
printf("\nSum of the %d Numbers = %d",counter, Sum);
printf("\nAverage of the %d Numbers = %.4f",counter, Average);
return 0;
}
I wrote a program which is able to take endless numbers of input add them into one variable and output the average of all the input numbers when the key 0 is pressed.
However, the problem is that when I type in for example 5 and 2 the sum variable has a value of 7. And counter has a value of 2.
However when the mathematical operation starts Average = SUM/Counter
, the
result is 3.00 not 3.500....
Anyone knows where my problem is?
Would appreciate any help.
Cheers
Marco
Upvotes: 1
Views: 65
Reputation: 1601
Average = Sum/counter;
Sum is int.
Average = (double)Sum/counter;
should do it. You need to typecast one of the operands to get the desired result, floating point in this case.
Upvotes: 5
Reputation: 96
I don't have the reputation to post comments. So I have to provide it as answer:
dbush's answer is more accurate:
You need to cast one of the operands, not the result.
Would you cast the result, it still were 3.00.
Upvotes: 0
Reputation: 224387
Sum
and counter
are both of type int
, so integer division is performed and their result is also of type int
.
You need to cast one of the operands to double
so that it does floating point division:
Average = (double)Sum/counter;
Upvotes: 3