Trying to convert float to int with type casting operator

Hi, I'm going through the tutorial and I'm on operators. When i enter the code demonstrating the explicit type casting operator and try to print it to the screen, it still shows it as a float with a value of 3.14, instead of the int value of 3 like the tutorial says it should be.
1
2
3
4
int i;
float f = 3.14;
i = (int) f;
cout << f;
Last edited on
You're outputting "f", which is the original float. That f is not going to change. The "i" variable, however, will be given the integer value of f. What happens in this code is that it'll go to assign i, it'll see "(int) f", it'll get the value of f, then it'll convert that value into an integer value, then assign it to i. Notice how it gets the value of f, but it doesn't change what f actually is. To make f into 3, you'd do:

1
2
3
float f = 3.14;
f = (int) f;
cout << f;


Now it'll output 3, because you changed the actual value of f.

At this point in your code, f = 3.14 and i = 3 . I think you may have meant to output i to begin with.
Last edited on
Yes, because you are printing f instead of i. You are casting the value of the variable f from float to integer, then assigning it to the i variable. So, the casted value is stored into the variable i.

 
cout << i;
Okay, thanks! I didn't think about that i should've remembered that these work right to left, Like it said earlier in the tutorial.
Topic archived. No new replies allowed.