谁能帮我弄清楚如何从两个不同长度的数组中获取总和。我尝试了很长时间但无法弄清楚。我知道我需要另一个循环。这是我到目前为止的食物
import java.util.Arrays;
import java.lang.*;
public class Question1d{
public static void main (String [] args){
double[] b = add();
System.out.println(Arrays.toString(b));
}
public static double[] add(){
double[] v = {1, 2, 3, 4, 5, 4};
double[] w = {5, 4, 3, 3, 1};
int a = v.length;
int b = w.length;
int capacity = Math.max(a,b);
double[] s = new double[capacity];
if (a==b){
for (int i = 0; i<capacity; i++){
s[i] = v[i] + w[i];
}
}
return s;
}
}
或者也许还有另一种方法。谢谢
编辑: 该方法应返回一个新的 double 数组,该数组是通过添加输入数组的相应元素而形成的。如果一个数组较长,则总和应获取该数组的元素,而另一个数组则需要考虑,因为它有 0 个值。
最佳答案
也许是这样的?
public static double[] add(){
double[] v = {1, 2, 3, 4, 5, 4};
double[] w = {5, 4, 3, 3, 1};
int a = v.length;
int b = w.length;
int capacity = Math.max(a,b);
double[] s = new double[capacity];
for (int i = 0; i<capacity; i++){
s[i] = (i >= v.length ? 0 : v[i]) + (i >= w.length ? 0 : w[i]);
}
return s;
}
关于java - 不同数组的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23481996/