dimanche 26 juin 2016

How does a static cast conserve a number's precision in C++?

After a long time without programming, I'm messing around with C++ for an assignment I have next month. I came upon the knowledge that variables can be overflown: specifically, float type variables will not hold as many decimals as double types. However, I tried this code:

#include <iostream>
#include <iomanip> 


int main()
{
    using namespace std;

    cout << setprecision(20);

    double t(0.1);
    float g(0.1);
    cout << t << endl;
    cout << g << endl;
    static_cast<float>(t);
    cout << t << endl;


}

And, to my surprise, the precision in both the first and the final (double t and float t) were the same, whereas the precision in float g was less. This seems somewhat counter intuitive to me, how does static_cast preserve the precision in the numbers?

Thank you very much.

Aucun commentaire:

Enregistrer un commentaire