DeltaAccel
DeltaAccel

Reputation: 9

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.

Upvotes: 0

Views: 403

Answers (2)

Alan
Alan

Reputation: 163

you didn't change the value of t.

using this below:

 cout << static_cast<float>(t) << endl;

or

t = static_cast<float>(t);  
  cout << t << endl;

Upvotes: 3

Jezor
Jezor

Reputation: 3426

That's because you didn't assign static_casted value to anything:

#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;
    g = static_cast<float>(t); // There was no assignment in your code
    cout << g << endl;
}

Output now:

0.10000000000000000555
0.10000000149011611938
0.10000000149011611938

Upvotes: 3

Related Questions