Your code isn't working for the same reason that this code:
int x = 5;
x + 5;
printf("%i", x);
does not print the number 10.
In C, (int)
is a type casting operator; much like the +
operator, it does not modify a variable; it creates an expression, which is evaluated and replaced by its result.
So the above code is equivalent to:
int x = 5;
10;
printf("%i", x);
In the same way, when you write (int) change;
you've only written an expression, which will be evaluated in place using the value of change
, without modifying change
itself. You have to explicitly do something with that value, or it just gets thrown away. In this case, "do something" probably means assigning the result of the expression to a new variable, since change
can only take float
type values.
change = change * 100;
change = roundf(change);
int cents = (int) change;
In fact, when you assign a float
value to a variable of type int
, the value will be silently truncated so that it can be stored as an integer, whether you include the explicit cast operator (int)
or not. When you do not explicitly cast the value, this is commonly referred to as type coercion:
change = change * 100;
change = roundf(change);
int cents = change;
If you are certain the value is (or should be) a whole number, even when stored as a float, you shouldn't have to worry about the truncation. But if you expect some decimal value, beware that truncation is equivalent to always rounding down, never up; a number like 5.9999
gets truncated to 5
if you coerce it to an integer.
You can also do the above three lines all in one step. Not only is this shorter code, it never modifies the original value of change
, which might be useful if you want to use it again somewhere else:
int cents = roundf(change * 100);
In this case I think it's more than sufficiently clear what's going on without explicit type casting. However, if you had declared int cents;
somewhere earlier in the code, it might make sense to add the (int)
operator in front of the expression to remind whoever's reading the code that the value being stored doesn't have the same type as change
.