5.7 public static int【】sumArray (int【】a ,int【】 b)要求返回的数组元素时两个参数数组对应的元素 ...

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 16:37   1070   0

1.

package bookTest3;

import java.util.Arrays;

public class FivePointSeven {
    /*
    编写一个方法,计算给定的两个数组之和,格式如下;
    public static int【】sumArray (int【】a ,int【】 b)
    要求返回的数组元素时两个参数数组对应的元素之和,不对应的元素直接赋值给相应的位置如:
    {1,2,4}+{2,4,6,8}={3,6,10,8}
     */
    public static int[] sumArray(int[] a,int[] b){
        int max = Math.max(a.length,b.length);
        a = Arrays.copyOf(a, max);
        b = Arrays.copyOf(b, max);
        int[] sumArray = new int[max];
        for (int i = 0; i <sumArray.length; i++) {
            sumArray[i] = a[i]+b[i];
        }
        return sumArray;
    }
    public static void main(String[] args) {
        int[] a = {1,2,4};
        int[] b = {2,4,6,8};
        int [] sun=sumArray(a,b);//新建一个数组 将数组固定住
        for (int i = 0; i <sun.length ; i++) {
            System.out.print(sun[i]+" ");
        }

        }
    }

2.结果图

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP