Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
726 views
in Technique[技术] by (71.8m points)

c - Why do we separately cast to "float" in an integer division?

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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...