Notice: Undefined offset: 12877959 in /var/www/html/qa-external/qa-external-users.php on line 744
Why 0.1+0.2 does not = 0.3 in c - OnlineGDB Q&A
Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

Why 0.1+0.2 does not = 0.3 in c

+6 votes
asked Oct 12, 2024 by Oliver 66 (290 points)

1 Answer

+1 vote
answered Oct 12, 2024 by Peter Minarik (101,340 points)
edited Oct 18, 2024 by Peter Minarik

It's called floating point precision. Numbers have limited precision and therefore what may look like a nice "round" mathematical operation may not so much look like for the computer dealing in binary number representations.

The following program produces 0.30000001192092895508 for floating point operations.

Would you increase the precision and use double instead of float, the result has better (but not perfect) precision: 0.30000000000000004441

#include <stdio.h>

int main()
{
    float fa = 0.1f;
    float fb = 0.2f;
    float fc = fa + fb;
    printf("float c = %.20f\n", fc);
    
    double da = 0.1d;
    double db = 0.2d;
    double dc = da + db;
    printf("double c = %.20lf\n", dc);

    return 0;
}

commented Oct 16, 2024 by Oliver 66 (290 points)
try to output 20 digits!
commented Oct 16, 2024 by Peter Minarik (101,340 points)
Good idea. I'll update my answer. Thank you.
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and receive answers from other members of the community.
...