when I run the code the result is -730512Code:
double x ;
x = 20 -730531.5;
cout<< x;
why?
shouldn't it be -730511.5
Printable View
when I run the code the result is -730512Code:
double x ;
x = 20 -730531.5;
cout<< x;
why?
shouldn't it be -730511.5
20 is an integer.
int - double = int....
Don't make me write a proof for it.
okay thanks but what shall I do to get result -730511.5
One would think so, but perhaps you don't use enough precision to show the decimals?
Something like this would show the exact value:
--Code:cout << fixed << x;
Mats
Nope, that's not how it works. If either side of an expression is a "bigger" type, the other side gets "promoted" to the "bigger" type, e.g. int + char or char + int makes the char int before adding, double + float makes the float double before adding, and int + double makes the int into double before add.
--
Mats
Actually, I'm wrong.
Output for me:Code:#include <iostream>
int main()
{
double y;
y = 730531.5;
std::cout << y << std::endl;
return 0;
}
Doubles and floats are just approximations. They aren't never 100% correct. This is probably what you're seeing.Code:730532
Actually, a double (assuming it's IEEE-754 64-bit variant) should be good enough for about 15 digits - and integers are never inaccurate - just limited in range, which is why we use floating point types to represent numbers outside of the integer range.
--
Mats
Try this:
Code:#include <iomanip>
...
std::cout << fixed << y << std::endl;
Here's why:
The default manipulator, "normal", is good for 6 digits. Had your example been 73053.5, it would have came out as you expected.
(I just learned this too!) Todd
I think I prefer printf()'s way of printing digits.
/me steps away as he starts another C vs C++ flamewar. :D :D :D
Now you're using your IBM hex-float format again. In IEEE-754 floating point, it's when the fraction can't be described precisely in binary, and the fraction is actually counted from the first number, so for example 0.1 is not precise, which means that all 2^n multiples of 0.1 are also subject to the same thing. 0.7 is the same sort of issue, along with several other numbers. 0.5 is not a problem, and 2^n * 0.5 is obviously also no problem.
--
Mats
I think we just said the same thing.