从int产品到long的隐式转换?

时间:2013-02-04 04:58:32

标签: java android implicit-conversion multiplication

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

这将是显式代码:

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

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

或者以下代码是否足够?

long baseDistanceSquare = baseDistance * baseDistance;

3 个答案:

答案 0 :(得分:1)

抓一点。我读错了。你必须强制转换它以防止溢出。

答案 1 :(得分: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

答案 2 :(得分:1)

正确的代码是:

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

施法值结束运行数学函数

其他例子:

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