'Why is the average coming out incorrectly in my C program?

#include <stdio.h>

int main(void) {
    float score1;
    float score2;
    float score3;
    float value;

    printf("Please enter three exam score: ");
    scanf("%f", &score1);
    scanf("%f", &score2);
    scanf("%f", &score3);
    printf("First exam:    %.1f", score1);
    printf("%%\\n");
    printf("Second exam:   %.0f", score2);
    printf("%%\\n");
    printf("Third exam:    %.0f", score3);
    printf("%%\\n");
    printf("-----------------------------------");

    value = (score1 + score2 + score3) / 3.0;

    printf("\\n");
    printf("Average:       %.14f",value);
    printf("%%.\\n");

    return 0;
}

-here is my code. the three scores are 75.5 92 100 and the average of these is 89.16666666666667%. but I am getting 89.16666412353516%. as the average when I run the program. any help is appreciated!

Thank you -Slurpski



Solution 1:[1]

Change float value; to double value; then you will get the value you want, which was 89.16666666666667.

Float is most likely a 32-bit IEEE 754 single precision Floating Point number (1 bit for the sign, 8 bits for the exponent, and 23 bits for the value). float has 7 decimal digits of precision.

Solution 2:[2]

1/6 is periodic in decimal, so it can't be represented exactly as a decimal floating point number. It would require infinite storage to do so. You claim 89.16666666666667 is correct, but it's not. You applied some rounding to obtain that.

1/6 is periodic in binary, so it can't be represented exactly by a floating point number. It would require infinite storage to do so. So some rounding must be applied. 89.16666412353515625 looks weird in decimal, but it's simply the correct number with some rounding applied in binary. Just like 89.16666666666667 is the closest number to the correct number after rounding in decimal, 89.16666412353515625 is the closest number to the correct number after rounding in binary. (This assumes the use of IEEE single-precision floating point number, which has 24 bits (~7 digits) of precision.)

Do you really need that many decimal places? I imagine it would be satisfactory to round the result to a decimal place or two.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2