1

如果 2 个int值的乘积不适合 a int,因此我将其存储在 along中,是否需要long在每个操作数之前(或至少在其中一个操作数之前)指定显式转换为?或者即使没有强制转换,编译器是否正确处理它?

这将是显式代码:

public final int baseDistance = (GameCenter.BLOCKSIZE * 3/2);

long baseDistanceSquare = (long)baseDistance * (long)baseDistance;

或者下面的代码就足够了吗?

long baseDistanceSquare = baseDistance * baseDistance;
4

3 回答 3

1

刮那个。我读错了。您必须强制转换它以防止溢出。

于 2013-02-04T05:00:44.833 回答
1

作为旁注,这相当于将整数运算的结果转换为浮点数的问题;例如:

    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
于 2013-02-04T05:28:46.203 回答
1

正确的代码是:

long baseDistanceSquare = (long)baseDistance * (long)baseDistance;

cast value end 运行一个数学函数

另一个例子:

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
于 2016-12-12T15:22:57.557 回答