Click to See Complete Forum and Search --> : Static Cast Error Truncation
DivZr0
July 18th, 2005, 03:34 PM
Hey all when I use the following code, and enter 300.34 it returns 30033, but that is the only value it returns one less for..... I don't understand why?
#include <iostream>
using namespace std;
int main() {
double d, temp;
int i;
cout << "Enter a number: ";
cin >> d;
i=static_cast<int>(d*100);
cout << "New Number: " << i;
return 0;
}
Thanks!
MrViggy
July 18th, 2005, 03:57 PM
Because the computer cannot represent 300.34 exactly. When it stores this in a float, it actually stores it as 300.3399999999999
Hence the value "30033" when you multiply by 100, and cast to an int.
Viggy
golanshahar
July 18th, 2005, 03:58 PM
i dont know why it happens :confused:
but i can suggest something to overcome it.
i=static_cast<int>(d*1000);
i/=10;
it will work but i really also wanna to know why its happening.
Cheers
DivZr0
July 18th, 2005, 04:05 PM
Because the computer cannot represent 300.34 exactly. When it stores this in a float, it actually stores it as 300.3399999999999
Hence the value "30033" when you multiply by 100, and cast to an int.
Viggy
I don't understand, wouldn't it do the exact same thing with 200.34 or any other number? But 300.34 is the only number that it happens with.
SuperKoko
July 18th, 2005, 05:07 PM
I don't understand, wouldn't it do the exact same thing with 200.34 or any other number? But 300.34 is the only number that it happens with.
MrViggy explained that 300.34 cannot be stored exactly with the binary representation of floats, so it stores something like 300.3399999999999
And, a conversion from float to int (a static_cast) is done by rounding to the greater integer not greater than 30033.99999999999, that is 30033
To avoid this error, you must round the floating number before casting it to int:
double fround(double val) // i don't know if there is any standard function to round a float number to the nearest integer.
{
double f=floor(val);
if (val-f>(f+1)-val) return f+1;
else return f;
}
// now use static_cast<int>(fround(d)*100);
Floating point numbers have floating point, that is, they are represented by a mantissa (a binary number) and an exponent (an other binary number), and a sign bit.
The value of the number is sign*mantissa*2^exponent
The best representation for a number whose value cannot be exactly represented, uses the whole mantissa bits, and the exponent can be negative.
200.34 and 300.34 have very different representations with a different exponent and a different mantissa.
SuperKoko
July 18th, 2005, 05:22 PM
Check the FAQ:
http://www.codeguru.com/forum/showthread.php?t=323835
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.