gpt4 book ai didi

java - 对值求和并将其存储到数组中

转载 作者:太空宇宙 更新时间:2023-11-04 06:28:01 25 4
gpt4 key购买 nike

将二维数组与数组相乘后得到以下结果。

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]);
}
}

最佳答案

您的结果不正确,但我认为您想要类似的结果

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);
}

关于java - 对值求和并将其存储到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26512319/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com