Reputation: 109
For example:
int number1 = 1, number2= 2;
float variable = (float)number1/(float)number2;
Instead of this, Why can't we use "float" only once? For example:
int number1 = 1, number2= 2;
float variable = (float)(number1/number2);
Upvotes: 3
Views: 4750
Reputation: 357
In the First case,
1/2 results 0
In the second case, you can use float once, but it has to be applied with one of the numbers before division
1.0/2.0 or 1.0/2 or 1/2.0 results 0.5
Upvotes: 0
Reputation: 227578
The objective is to avoid the truncation that comes with integer division. This requires that at least one of the operands of the division be a floating point number. Thus you only need one cast to float
, but in the right place. For example,
float variable = number1/(float)number2; // denominator is float
or
float variable = ((float)number1)/number2; // numerator is float
Note that in the second example, one extra set of parentheses has been added for clarity, but due to precedence rules, it is the same as
float variable = (float)number1/number2; // numerator is float, same as above
Also note that in your second example,
float variable = (float)(number1/number2);
the cast to float
is applied after the integer division, so this does not avoid truncation. Since the result of the expression is assigned to a float
anyway, it is the exact of
float variable = number1/number2;
Upvotes: 11
Reputation: 755026
You can write either expression, but you get different results.
With float variable = (float)(number1 / number2);
the value in variable
is 0, because the division is done as integer division, and 1/2 is 0, and the result is converted.
With float variable = (float)number1 / (float)number2;
, the value in variable
is 0.5, because the division is done as floating point division.
Either one of the casts in float variable = (float)number1 / (float)number2;
can be omitted and the result is the same; the other operand is converted from int
to float
before the division occurs.
Upvotes: 4
Reputation: 16777
Since number1
and number2
are int
s, the division performed will be integral division. Thus, number1/number2
will evaluate to the int
0. To do floating point arithmetic instead, you need to cast them. Note that simply casting one will suffice, since the other one will be implicitly promoted. So, you can just say ((float)number1)/number2
.
Upvotes: 0