如何减去两个数组

时间:2017-05-27 18:44:02

标签: java arrays subtraction

我有两个数组:A和B.我想减去它们的值,并将结果存储在数组C中。

伪代码:

Array A[] = (2,2,2)
Array B[] = (1,1,1)

我想让A-B创建数组C:

Array C[] = (1,1,1)

我的代码:

int []A = new int[3];
for (int i=0; i<3; i++){
    A[i]=IOHelp.readInt("Input numbers as you desire"+i);
}
System.out.println( "The number of  A  array are=("+A[0]+","+A[1]+","+A[2]+")");

// Exact same code for array B.
// Omitted for brevity.

int[] d = new int[3];
for(int i = 0; i <3; i++){
    d[i] = B[i] - A[i];
}
System.out.println("BA=("+d[0]+","+d[1]+","+d[2]+")"); // Prints a new array in this format: BA=(number1, number2, number3)

现在我在设置条件时遇到了一些问题。

1 个答案:

答案 0 :(得分:2)

假设数组A和B具有相同的长度:

int[] a = {2, 2, 2};
int[] b = {1, 1, 1};
int[] c = new int[a.length];

for(int i = 0; i < a.length; i++){
    c[i] = a[i] - b[i];
}