Tuesday, July 14, 2009

Why does Visual C++ change the value of my variable?

I'm a beginner in C++, and I've defined a double variable (exh) as 100.0015. But when I run the program, the number changes to 100.0014999... what is going on?

Why does Visual C++ change the value of my variable?
because floating point numbers are defined in computer logic as


NUMBER * 2^X, where X and number are stored in the computer, this leaves a little inaccuracy, because not every number in base 10 can be represented this way. Which leads to the first rule of programming:





Never compare floating point numbers for equality.





Instead compare them for "close enough"-ness. Such as:


float a,b,c;


if((a - b) %26lt; .000001)


{


cout %26lt;%26lt; "Number's are \"equal\""


}
Reply:Not all decimal floating numbers can be represented exactly the same in binary floating point format. It's the same number or as close as you are going to get, 100.0014999~. This is why you should always use format specifiers when printing out floating point numbers. A format specifier says how many digits to the left and/or right of the decimal point that you wish to print out, and will round the number properly.


No comments:

Post a Comment