1

Here is the code:

#include <iostream>
#include <math.h>

double f(double d)
{
    double num1 = d*sqrt(5.0);
    double num2 = sqrt(5.0*d*d+4.0);
    double phi = (1.0 + sqrt(5.0))/2.0;

    return log((num1+num2)/2.0)/log(phi);
}

int main()
{
    double double_val = f(8);
    std::cout << "double_val: " << double_val << std::endl;
    int int_val = static_cast<int>(double_val);
    std::cout << "int_val: " << int_val << std::endl;
}

Running the code online results in the following output:

double_val: 6
int_val: 5

This surprised me greatly. Why would a double printed as 6 sometimes get casted to an integer which is printed as 5?

BlueTune
  • 1,023
  • 6
  • 18
  • 1
    `double_val` is a tiny bit less than 6 so truncates to 5: https://godbolt.org/z/cPX2vb – Alan Birtles Mar 14 '20 at 12:33
  • Just in passing: this has nothing to do with `static_cast` (or any other form of cast); it's about the **conversion** that's being done because of the cast. You'd get the same result without the cast: `int int_val = double_val;`. – Pete Becker Mar 14 '20 at 14:40
  • Yes, thanks to Alan Birtles the issue is solved using `std::cout << "double_val: " << std::setprecision(30)`. – BlueTune Mar 14 '20 at 14:47

0 Answers0