Reputation: 33
I would like to avoid 'floating point error in this code.
A purpose of this code is to gain 'The average of whole numbers' but the number of 'whole numbers' is limited by the input of users. Please help me.
#include <stdio.h>
int main(void)
{
int num=0;
int limit;
int result=0;
printf("number of integer: ");
scanf("&d", &limit);
while(num<limit)
{
int output;
printf("Input integer : ");
scanf("%d", &output);
result += output;
num++;
}
printf("average of total integer: %d \n", result/limit);
return 0;
}
Thank you for reading.
Upvotes: 3
Views: 322
Reputation: 2183
As the result of two integer
dividing is also an integer,so it as
printf("average of total integer: %f \n", result/(float)limit);
when you type cast the variable limit
to float what happens is that result
will be implicitly converted to float
and so the result is a float
.
Upvotes: 1
Reputation: 11180
When you divide 2 integers, the result is also an integer.
To return a float, you need to cast one of the arguments as a float.
So your last line becomes
printf("average of total integer: %f \n", result/(float)limit);
Upvotes: 3