开发者

float/int implicit conversion

开发者 https://www.devze.com 2023-01-23 18:05 出处:网络
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 googl开发者_Go百科e more quickly than asking here)

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 googl开发者_Go百科e 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?


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


To demonstrate:

 int i1 = 5;
 float f = 0.5f;
 int i2 = 2;
 System.out.println(i1 * f);
 System.out.println(i1 / i2);
 System.out.println(((float) i1) / i2);

Result:

2.5
2 
2.5


In order to perform any sort of floating-point arithmetic with integers, you need to convert (read: cast) at least one of the operands to a float type.


If at least one of the operands to a binary operator is of floating-point type, then the operation is a floating-point operation, even if the other is integral.

(Source: Java language specifications - 4.2.4)

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

System.out.println(((Object)(1f*1)).getClass());//class java.lang.Float

(If you use DrJava, you can simply type ((Object)(1f*1)).getClass() into the interactions panel. There's a plugin for DrJava for Eclipse too.)


The simple answer is that Java will perform widening conversions automatically but not narrowing conversions. So for example int->float is automatic but float->int requires a cast.


Java ranks primitive types in the order int < long < float < double. If an operator is used with different primitive types, the type which appears before the other in the above list will be implicitly converted to the other, without any compiler diagnostic, even in cases where this would cause a loss of precision. For example, 16777217-1.0f will yield 16777215.0f (one less than the correct value). In many cases, operations between a float and an int outside the range +/-16777216 should be performed by casting the int to double, performing the operation, and then--if necessary--casting the result to float. I find the requirement for the double casting annoying, but the typecasting rules in Java require that one either use the annoying double cast or suffer the loss of precision.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号