[英]Sum of different arrays
誰能幫助我找出如何從2個不同長度的數組中求和。 我正在嘗試很長時間,但無法弄清楚。 我知道我需要另一個循環。 直到現在這是我的食物
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;
}
}
也許還有另一種方法。 n
eddit:該方法應返回一個新的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;
}
如果要計數兩個數組的和,只需對第一個數組的和進行計數,然后對第二個數組的和進行計數,最后對這兩個數字的和進行計數。
int sum1 = 0;
for (int i : v)
sum1 += i;
int sum2 = 0:
for (int i : w)
sum2 += i;
int result = sum1 + sum2;
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.