Why does a1=72 instead of 73 in this (terrible) snippet of C++ code ?
#include <iostream>
#include <string>
using namespace std;
int main (int argc, char* argv[])
{
double a = 136.73;
unsigned int a1 = (100*(a-(int)a));
cout << (a-(int)a) << endl; // 0.73
cout << 100*(a-(int)a) << endl; // 73
cout << a1 << endl; // 72 !
}
You can execute it at http://codepad.org/HhGwTFhw
If you increase the output precision, you’ll see that
(a - (int) a)prints0.7299999999999898.Therefore, the truncation of this value (which you obtain when you cast it to an
int) is indeed72.(Updated codepad here.)