Tuesday, July 14, 2009

Problem in reading floating point numbers using Dev-cpp?

I'm having problem in reading some floating point numbers in C. When I use fstream and read say 4.56 - it stores it as 4.5599999999999.





I know from theory that 4.5599999... and 4.56 are equal but I need 4.56 not the one with infinite 9s.





So please help me. Is there a way I can read it as 4.56 or if not is there a function I can use to convert 4.5599999 to 4.56?

Problem in reading floating point numbers using Dev-cpp?
You can't help the input conversion -- decimal fractions don't always (all right, rarely) convert exactly to binary fractions, and the input conversion has to live with that. But you can control the output so that it looks tidier. Study the standard C output format conversions, the f conversion in particular, and limit the number of decimal places. %.2f in this case. That should produce the rounded result you're looking for.





Good luck.
Reply:My gut instinct is that it is a problem with your compiler. You may want to get a different compiler:





http://openlist.asponge.com/getInfo.php?...
Reply:to get clean output, you need to use the formatting specifications in your printf statement. For two digits after the decimal point, use %.2f





There is never a guarantee that internally floating point numbers will match exactly, even if math says that they should. Many times when a computer adds, subtracts, multiplies, or divides floating point numbers a little bit of error will creep in.


No matter how many bits it uses, the representation is always an approximation. In decimal notation, it takes an infinite number of digits to write the value 1/3. 0.3333 is an approximation. 0.333333333333333333 is better, but still an approximation. Since a floating point number is stored in binary, 0.2 is infinitely repeating like 1/3 in the decimal system.


Integers do not have this problem. You might try using an internal representation that multiplies everything by 100. then divide it just before you print it.


No comments:

Post a Comment