Ad space (banner)
๐Ÿ”งC Lessons
Lesson 57 / 68

Watch Out for Floating-Point Rounding Errors

This lesson covers floating-point precision errors in C, so you understand why a decimal calculation can produce an unexpected result. It's for anyone searching "C floating point precision error."

Because a computer represents decimals in binary, even a simple calculation like 0.1 + 0.2 doesn't always come out to exactly 0.3. Display it and the error shows up directly, and comparing it evaluates to false.

The example uses the high-precision format specifier printf("%.17g ", a) to display a value with a visible error, and confirms a == 0.3 evaluates to false. This is a phenomenon common to most programming languages that handle floating-point numbers.

A common early mistake is comparing two decimals directly with == and not getting the expected result. Knowing this error comes from the IEEE 754 international standard deepens your understanding of why it happens.

In real projects, working in integers (like cents instead of dollars) is a technique used for calculations, like monetary ones, where accuracy really matters.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run C directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)