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

Categories

I'm doing multiplication and division of floats and ints and I forget the implicit conversion rules (and the words in the question seem too vague to google more quickly than asking here).

If I have two ints, but I want to do floating-point division, do I need only to cast one or both of the operands? How about for multiplication — if I multiply a float and an int, is the answer a float?

See Question&Answers more detail:os

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

1 Answer

You can’t assign to an int result from division of a float by an int or vice-versa.

So the answers are:

If I have two ints, but I want to do floating point division…?

One cast is enough.

If I multiply a float and an int, is the answer a float?

Yes it is.


float f = 1000f;
int i = 3; 

f = i; // Ok
i = f; // Error

f = i/f; //Ok 0.003
f = f/i; //Ok 333.3333(3)

i = i/f; //Error
i = f/i; //Error

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...