假设数组一 [2/3, 0, -1, 0, 7/2]
和数组二 [0, 0, -2/3, 1, 0, 0]
所以我希望结果数组为 [0, 2/3, -2/3, 0, 0, 7/2]
。结果数组长度将是两个数组之间的最大长度。我怎样才能在Java中做到这一点?
我非常希望特定的索引位置相互添加,但我不知道如何使用不相等的数组来做到这一点。
编辑:它添加位置,并且任何不匹配的内容在最大数组中保持不变。 [0, 0, -2/3, 1, 0, 0]
具有位置 0, 1, 2, 3, 4, 5
和数组 [2/3, 0, -1, 0, 7/2]
的位置与较大的数组 1, 2, 3, 4, 5
一致,所以我想要相同的位置值要添加并放入结果数组中。我创建了一个新的结果数组并将其设置为等于最大数组,因此所需要做的就是添加相似的位置值。
最佳答案
这是我设计的一种详细且易于理解的方法:
它的作用是将数组的最后一个元素添加在一起并从那里向后移动;如果一个数组先于另一个数组结束,它只是用零替换不存在元素的值,然后将它们相加:
public class ArrayAddition
{
public static void main(String[] args)
{
double array1[] = {2./3, 0, -1, 0, 7./2}; // first array
double array2[] = {0, 0, -2./3, 1, 0, 0}; // second array
int length = Math.max(array1.length, array2.length); // length of longest array
double newArray[] = new double[length]; // result must be length of longest array
int index1 = array1.length - 1; // last element of first array
int index2 = array2.length - 1; // last element of second array
int indexRes = length - 1; // result will be placed in last spot of result
for (int i = length -1; i >= 0; i--) // adds elements of two arrays together bckwrd
{
double val1, val2; // value holders for array elements
try // try to get value of the array 1 at certain position
{
val1 = array1[index1];
}
catch(ArrayIndexOutOfBoundsException e) // if empty, make it zero
{
val1 = 0;
}
try // try to get value of array 2 at certain position
{
val2 = array2[index2];
}
catch(ArrayIndexOutOfBoundsException e) // if empty make it zero
{
val2 = 0;
}
newArray[indexRes] = val1 + val2; // array[?] result is val1 + val 2
index1--; // decrement to the next lower value
index2 --; // decrement to the next lower value
indexRes--; // go the next lower spot
}
for (int i = 0; i < newArray.length; i ++) // this loop prints out the results
System.out.println(newArray[i]);
}
}
您需要输入 double 值,否则答案将不正确(2./3 而不是 2/3)
0.0
0.6666666666666666
-0.6666666666666666
0.0
0.0
3.5
出于显而易见的原因,答案将采用十进制形式(如果答案是 2/3,它实际上将 2 除以 3,仍然是正确的答案,您可以将其转换回来)
希望这有帮助! :)
关于Java - 添加两个不相等数组的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19352094/