2013-02-04 87 views
1

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

这将是明确的代码:

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

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

或者是下面的代码是否足够?

long baseDistanceSquare = baseDistance * baseDistance; 
+0

Downvoter,护理解释你downvote?或者stackoverflow不允许初学者访问? –

回答

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 
1

划痕。我读错了。你必须施放它来防止溢出。

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 
相关问题