Rodekki
Rodekki

Reputation: 25

Implementing a type cast

so I'm having trouble figuring out where I should be implementing the type cast for my code. I understand the purpose of type casting, but I just don't get (or am over thinking) where exactly it should go for my given situation.

So I have a function. It's going to take the input and print it out in hexadecimal form.

void PrintHex(int InNum)
{
cout << hex << setiosflags (ios_base::showbase) << InNum;
};

The thing is, it's not going to be receiving an int as expected, but rather a float from a member function of my class.

float Sphere::CalcCircumference()
{
return (Pi * (Radius*2));
};

I need to type cast the float to an int to avoid a loss of precision. But exactly where do I do this? I get a feeling I might need to do it in the member function that determines the Circumference, returning the outcome in static form. But I'm not sure.

Upvotes: 0

Views: 117

Answers (2)

ozox
ozox

Reputation: 472

Your question is confusing: you mentioned you do not want to lose precision, but casting a float to an int will cause the precision loss. E.g.,

float i = 1.3;
int j = (int)i; // j get the value 1

I'm guessing you want to print the content of the float variable as an int, so you don't lose any precision. If that is the case, here is the way:

float i = 1.3;
int j = *((int*)&i); // j get the int representation value of i

I hope you understand the round-off error for float type. In computers, there is no such thing that represent, for example, 0.2 precisely. So floating point always has some small errors. But that's out of the scope of this function.

Upvotes: 3

Pete Becker
Pete Becker

Reputation: 76523

You don't need a typecast. Just call your function:

PrintHex(sphere.CalcCircumference());

The compiler will convert the float to int in exactly the same way as a typecast would.

Upvotes: 0

Related Questions