繁体   English   中英

汇总值并将其存储到数组中

[英]sum up values and store it into array

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

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

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

假设您有此数组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}; 和result [] = new int [12];

for (int i = 0; i < result.length; i++) {
 result[i] = firstResults[0+(i*2)] + firstResults[1+(i*2)];
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM