Home > database >  Why is the average coming out incorrectly in my C program?
Why is the average coming out incorrectly in my C program?

Time:03-30

#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

CodePudding user response:

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.

CodePudding user response:

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 is the closest attainable with as IEEE single-precision floating point number, which has only 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.

  • Related