此方法用于获取(通过用户输入)给定数据集中的两个最大整数并计算它们的乘积。它适用于每个输入,直到我尝试使用两个整数数组 100000
和 90000
并返回 410065408
。
这是我的 Java 方法:
static int getMaxPairwiseProduct(int[] numbers) {
int max=0,lessermax=0;
int n = numbers.length;
for (int j = 0; j < n; ++j) {
//if(j==k)continue;
if(numbers[j]>0 && numbers[j]>=max) {
lessermax=max;max=numbers[j];
System.out.println(j);//k=j;
} else if(numbers[j]>lessermax) {
lessermax=numbers[j];
System.out.println(j);}
}
//result=;
return max*lessermax;
}
这是我的main
方法:
public static void main(String[] args) {
//FastScanner scanner = new FastScanner(System.in);
Scanner scanner=new Scanner(System.in);
int n = scanner.nextInt();
int[] numbers = new int[n];
for (int i = 0; i < n; i++) {
numbers[i] = scanner.nextInt();
}
scanner.close();
System.out.println(getMaxPairwiseProduct(numbers));
}
最佳答案
int
的容量已溢出并环绕。 100000 * 90000
是 9000000000
。 int
的最大正值是 2^31-1,即2147483647
(略小于 9000000000
的四分之一)。
如果您想要这两个数字的乘积,则需要使用 long
相反。
100000L * 90000L = 9000000000L = 0x218711a00L
对于 32 位数据类型,32 位(8 个十六进制数字)之外的任何内容都会因溢出而被截断。所以剩下的值为:0x18711a00
== 410065408
关于java - 将两个大整数值相乘会得到不正确的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38170989/