java实现一个数组倒序后和另一个数组相加,这样写有什么问题?

public static void main(String[] args)
{
int[] a = {1,2,4,5,8};
int[] b = {2,3,4,5,9};
Test test = new Test();

System.out.println(test.arrAdd(a, b));
}
public int[] arrAdd(int[] a,int[] b)
{
int temp;
int[] outArry = new int[a.length];
for(int i=0;i<=b.length/2;i++)
{
temp = b[i];
b[i]=b[b.length-1-i];
b[b.length-1-i]=temp;
}
for(int j=0;j<a.length;j++)
{
outArry[j]=a[j]+b[j];
}
return outArry;
}

第1个回答  2012-11-05
有错误,你的for循环的结束条件是有问题的,应该是i < b.length / 2才对。
因为对于一个偶数个数的数组做反序,我们只需要对调length / 2次,这是没错的,但是java的数组起始位置是0,相当于执行到length / 2 - 1的时候,数组就已经反序好了,但是你又多执行了一次,结果导致的就是最中间的两个数又变回去了。本回答被网友采纳
第2个回答  2012-11-07
真正的问题是效率太低了 童鞋,看这个

public static void main(String[] args){
int[] a = {1,2,4,5,8};
int[] b = {2,3,4,5,9};
int length=a.length;
for (int i = 0; i < length; i++) {
System.out.print(a[i]+b[length-i-1]+",");
}
}
第3个回答  2012-11-05
有什么问题?结果就是:10,7,8,8,10呀,对的呀。
第4个回答  2012-11-05
你运行时出了啥问题啊?
相似回答