Question

Within a member function of a class used as a template paramter, I have a function containing the following code:

double x = /*Something operation returning double*/;
x /= CubeWidth; /*CubeWidth is a class member*/
cout << "Element after centering and normalization = " << x << endl;
cout << "and after adding 1 and truncating = " << x+1 << endl;
cout << "then static cast = " << (int) x+1 << endl;

The output of this function is

Element after centering and normalization = 1
and after adding 1 and truncating = 2
then static cast = 1

Obviously, the last line should give an answer 2.

If I instantiate exactly the same class without using it as the template parameter, I don't get this printout, rather I have the correct one.

Can anyone tell me why this is happening?

Was it helpful?

Solution

Most likely x (a double) is not exactly 1, it is 0.9999999.... Check its exact value by printing x==1.0 or x<1.0 and see what is really true. Or add more digits to the output:

cout << "and after adding 1 and truncating = " << setprecision( 15 ) << x+1 << endl;

The rounding to integer will throw away all digits after the comma, so 1.999999... becomes 1.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top