2 回答
TA贡献1833条经验 获得超4个赞
首先,您必须找到输出数组的大小。
int h = a.length>b.length?a.length:b.length;
int w = a[0].length>b[0].length?a[0].length:b[0].length;
int[][] result = new int[h][w];
然后做你的任务。
for(int i = 0; i<result.length; i++){
for(int j = 0; j<result[i].length; j++){
if(i<a.length && j < a[i].length){
result[i][j] += a[i][j];
}
if(i<b.length && j < b[i].length){
result[i][j] += b[i][j];
}
}
}
return result;
TA贡献2036条经验 获得超8个赞
使用此代码。只需使尺寸标识部分动态化
import java.util.Arrays;
public class Main
{
public static void main (String[]args)
{
System.out.println ("Hello World");
int m1 = 3, n1 = 1, m2 = 2, n2 = 4; // m1 and n1 are matrix 'x' dimensions and m2 & n2 are natrix 'y' dimensions
int x[][] = {
{1},
{2},
{3}
};
int y[][] = {
{1, 2, 1, 2},
{1, 2, 1, 2}};
int op[][] = new int[m1][n2];
for (int[] row: op)// filling empty matrix with zeroes
Arrays.fill(row, 0);
for (int i = 0; i < m1; i++)
{
for (int j = 0; j < n1; j++)
{
op[i][j] = x[i][j];
}
}
int op2[][] = new int[m1][n2];
for (int[] row: op2)// filling empty matrix with zeroes
Arrays.fill(row, 0);
for (int i = 0; i < m2; i++)
{
for (int j = 0; j < n2; j++)
{
op2[i][j] = y[i][j];
}
}
for(int i=0;i<m1; i++)
{
for(int j=0;j<n2;j++)
{
System.out.print((op[i][j]+op2[i][j])+" ");
}
System.out.println();
}
}
}
添加回答
举报