> I'm (very) new to c++ and I'm having trouble understanding why this
doesn't
work. Here's some testcode:
#include <iostream.h>
int main()
{
float test;
unsigned int test2;
test = 1.8;
cout << "\n" << test*100.0 << endl;
test2 = static_cast<unsigned int>(test*100.0);
cout << "\n" << test2 << endl;
}
The strange thing is that the program returns 180 on the first cout
(as expected) but it returns 179 on the second ???
If I make test 1.7, I get 170 on the first and second cout ???
I tried a whole bunch of other values... Sometimes I'm getting what I
expected, sometimes not...
Can anyone explain this to me ?
This is caused by the way the float type store number internally. Some
numbers cannot be exactly represented in floating point format; only a
approximation of the number is stored. Because of this 1.8*100.0 may
produce 179.9999952. The reason you see 180.000 is because the result is
rounded before it is printed. When you change the line that outputs the
floating point value to:
cout << "\n" << std::setprecision(10) << test*100.0 << endl;
You will probably see that test*100.0 is not exactly 180.0
When casting to in the part behind the decimal point will be truncated
so the result will be 179.
This is also the reason why comparing two floating point values with the
== operator is usually wrong. For example the program below will (most
likely) output the text "Not equal", because the number 1.23 cannot be
exactly represented in IEEE-754 floating point format (which most
implementations use for floating point numbers):
#include <iostream>
int main()
{
float f = 1.23;
if(f*2 == 2.46)
{
std::cout << "Equal\n";
}
else
{
std::cout << "Not Equal\n";
}
return 0;
}
--
Peter van Merkerk
peter.van.merkerk(at)dse.nl