#include <iostream>
#include <cmath>
usingnamespace std;
double INT_LENGTH(int a){
for(double i=0; true; i++,a/=10)
if(!a) //returns number of
return i; //digits of an int
}
int main()
{
int m=5553;
int n=9;
cout<<"m="<<m+(n%10)*pow(10,INT_LENGTH(m))<<endl; //<-- why THIS line...
m+=(n%10)*pow(10,INT_LENGTH(m)); //
//
cout<<"m="<<m; //<-- ...and THIS line
// produce different
return 0; // results!?
}
The output I get is:
m=95553
m=95552
Why lines 17 and 20 produce different results in the cout?
Why does the value of 'm' get decreased by 1 when I calculate it?
EDIT:
In C++ Shell, the code produces the results as it should (95553 in both lines). But in CodeBlocks, at least mine, it produces the output I specified. Is that a bug or something?
What compiler are you using? Debug MS VS Express 2013 gives be 95553 for both results. I'd suspect it might be a truncation or rounding issue, though, as the result you are sending to cout is a double while assigning to m truncates to int.
The (GCC) compiler has options for changing how it implements floating point math. Seek "man gcc" with 'math'.
I'd guess that description of option '-mpc80' relates here. The CPU has "extended precision" registers.
The result of pow() is probably converted directly from register into an int.
The other path rounds the content of register into a double. That is where the precision is "lost".
(Just a guess. Floating point math is weird, strange, and bewildering.)
Just wondering why you used double in the for loop on line 7? Why not an intbecause you are counting how times you can divide by 10?
And why this academic question of using intwith the pow function? Perhaps it is an arbitrary & obfuscated example to demonstrate the dangers of FP. We may as well have a discussion about why 10 * 0.1 != 1.0
I am sure the pow function uses a series to calc the answer: so assigning to intand expecting a good answer doesn't make sense to me.
What is the result of 9%10? More to the point why?