Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
635 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 Reply

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...