【发布时间】:2018-08-26 12:13:46
【问题描述】:
我正在尝试将一个数字数组中的两个最大数字相乘。它适用于小数字。
正确的输入/输出 - 这是有效的:
3 10 2 8 80
正确的输入/输出 - 这是失败的:
2 100000 90000
9000000000
然而,我的输出是 10000000000。
谁能告诉我我的代码有什么问题?
public static Long sumPairwise(Long[] numbers){
int index=0;
int n = numbers.length;
for(int i=1;i<n;i++){
if(numbers[i]>numbers[index])
index=i;
}
numbers[n-1]= numbers[index];
index=0;
for(int j=1;j<n-1;j++){
if(numbers[j]>numbers[index])
index=j;
}
numbers[n-2]=numbers[index];
Long product = (numbers[n-2])*(numbers[n-1]);
return product ;
}
public static void main(String [] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Long numbers[] = new Long[n];
for (int i=0;i<n;i++)
numbers[i]= sc.nextLong();
System.out.println(sumPairwise(numbers));
}
【问题讨论】:
-
寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包括所需的行为、特定的问题或错误以及在问题本身中重现它所需的最短代码。没有明确问题陈述的问题对其他读者没有用处。请参阅:如何创建 minimal reproducible example。使用edit 链接改进您的问题 - 不要通过 cmets 添加更多信息。谢谢!
标签: java multiplication