![](/img/trans.png)
[英]Why is this long overflowing to -1, instead of the minimum value for the type?
[英]I have tried using long both as the variable type as well as the return type of the function but still it is overflowing. I cannot understand why?
我正在调用getMaxPairwiseProduct()方法,但它返回“产品”变量的溢出值。 我已经在使用多头了,产品实际上在多头的极限内,但是我不明白为什么它返回溢出值。
import java.util.Scanner;
public class MaxPairwiseProduct {
static long getMaxPairwiseProduct(int[] array){
//int product =0 ;
int n = array.length;
//for(int j =0; j<n ; ++j){
//}
QuickSort(array, 0, array.length -1 );
int n1 = (array[array.length-1]);
int n2 = (array[array.length-2]);
long product =n1 * n2;
System.out.println(product);
return product;
}
private static void QuickSort(int[] arr, int left, int right){
int index = partition(arr,left, right);
if(left < index - 1)
QuickSort(arr, left, index -1);
if(index < right)
QuickSort(arr, index, right);
//System.out.println(index);
}
private static int partition(int[] arr, int left, int right){
int pivot = arr[(left + right )/2];
while(left<=right){
while(arr[left] < pivot) left++;
while(arr[right] > pivot) right--;
if(left<= right){
int temp= arr[left];
arr[left] = arr[right];
arr[right] =temp;
left++;
right--;
}
}
return left;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
/*int n = sc.nextInt();
int[] array = new int[n];
for(int i=0; i <n;++i){
array[i] = sc.nextInt();
}
*/
int[] array = new int[]{100000, 90000};
long product = getMaxPairwiseProduct(array);
System.out.println(product);
}
}
长话短说,在Java中,默认情况下,每个整数(非十进制)数字都被视为int
,您的行:
long product =n1 * n2;
将两个将溢出的int
值相乘,只有获得溢出的结果后,它才会转换为long并保存在product
变量中。
解决?
将两个操作数之一显式转换为long
,这样可以正常工作:
long product = (long)n1 * n2;
Java将自动开始使用“最大”数据类型,因此,由于您将long
和int
相乘,因此int
或n2
也将隐式转换为long
,因此不会发生溢出,并且应该得到正确的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.