Java 从int乘积到long的隐式转换?
如果2个Java 从int乘积到long的隐式转换?,java,android,implicit-conversion,multiplication,Java,Android,Implicit Conversion,Multiplication,如果2个int值的乘积不适合int,因此我将其存储在long中,我是否需要在每个操作数之前(或至少在其中一个操作数之前)指定显式转换为long?或者即使没有强制转换,编译器也能正确处理它吗 这将是明确的代码: public final int baseDistance = (GameCenter.BLOCKSIZE * 3/2); long baseDistanceSquare = (long)baseDistance * (long)baseDistance; 或者下面的代码是否足够 lo
int
值的乘积不适合int
,因此我将其存储在long
中,我是否需要在每个操作数之前(或至少在其中一个操作数之前)指定显式转换为long
?或者即使没有强制转换,编译器也能正确处理它吗
这将是明确的代码:
public final int baseDistance = (GameCenter.BLOCKSIZE * 3/2);
long baseDistanceSquare = (long)baseDistance * (long)baseDistance;
或者下面的代码是否足够
long baseDistanceSquare = baseDistance * baseDistance;
把它擦掉。我看错了。您必须强制转换它以防止溢出。作为旁注,这相当于将整数运算的结果转换为浮点运算的问题;例如:
float f = 2/3;
System.out.println(f); // Print 0.0
f = (float)(2/3);
System.out.println(f); // Print 0.0
f = (float)2/3;
System.out.println(f); // Print 0.6666667
int X;
long Y, Z;
Z = X * Y; // Result is int value
Z = (long) X * Y //Result is long value
Z = X * 1L //Result is long value
正确的代码是:
long baseDistanceSquare = (long)baseDistance * (long)baseDistance;
浇铸值结束运行一个数学函数
其他例子:
float f = 2/3;
System.out.println(f); // Print 0.0
f = (float)(2/3);
System.out.println(f); // Print 0.0
f = (float)2/3;
System.out.println(f); // Print 0.6666667
int X;
long Y, Z;
Z = X * Y; // Result is int value
Z = (long) X * Y //Result is long value
Z = X * 1L //Result is long value
反对票,你想解释一下你的反对票吗?或者初学者不再允许访问stackoverflow?