在将2d数组与数组相乘后,我得到以下结果。
76,0,38,7,32,0,16,18,32,0,16,18,0,0,0,19,16,0,8,23,76,0,38,25
现在我想将值2加2并将其存储在另一个数组中(results []) 所以它就像
76 + 0 = 76(results[0])
38 + 7 = 45(results[1)
32 + 0 = 32(results[2])
16 + 18 = 34(results[3])
32 + 0 = 32(results[4])
16 + 18 = 34(results[5])
0 + 0 = 0(results[6])
0 + 19 = 19(results[7])
16 + 0 = 16(results[8])
8 + 23 = 31(results[9])
76 + 0 = 76(results[10])
38 + 25 = 63(results[11])
但我得到了这个结果而不是
114
7
48
18
48
18
0
19
24
23
114
25
请帮忙。
public static void main(String argv[]) {
int matrix[][]= { {4,0},
{2,1},
};
int array[] = {19,7,8,18,8,18,0,19,4,23,19,25};
int result[] = new int[12];
for (int count = 0; count < array.length; count+= matrix.length) {
for (int r = 0; r < matrix.length; r++) {
for (int c = 0; c < matrix.length; c++) {
result[count] += matrix[r][c] * array[count++];
}
count -= matrix.length;
}
}
for(int i = 0; i < result.length; i++) {
System.out.println(result[i]);
}
}
答案 0 :(得分:1)
你的结果不正确,但我认为你想要像
这样的东西int matrix[][] = { { 4, 0 }, { 2, 1 } };
int array[] = { 19, 7, 8, 18, 8, 18, 0, 19, 4, 23, 19, 25 };
List<Integer> result = new ArrayList<>();
for (int i = 0; i < array.length; i++) {
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[0].length; col++) {
result.add(array[i] * matrix[row][col]);
}
}
}
System.out.println(result); // <-- display the result of matrix multiplication.
// Add pairs.
for (int i = 0; i + 1 < result.size(); i += 2) {
int a = result.get(i);
int b = result.get(i + 1);
int total = a + b;
System.out.printf("%d. %d + %d = %d%n", i, a, b, total);
}
答案 1 :(得分:0)
假设你有这个数组firstResults [] = {76,0,38,7,32,0,16,18,32,0,16,18,0,0,0,19,16,0, 8,23,76,0,38,25}; 和结果[] = new int [12];
for (int i = 0; i < result.length; i++) {
result[i] = firstResults[0+(i*2)] + firstResults[1+(i*2)];
}