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;
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…