如何编码数组的总和?

时间:2018-08-14 06:20:39

标签: java arrays

每当我尝试对其进行编译时,输出均为0。不知道为什么,但是请任何人帮助。

 public static void main(String[] args) {

    int array1[ ] = {1,2,3};
    int array2[ ] = {10,9,8};
    int[] c = new int[array1.length];


    for(int i = 0; i<array1.length ; i++){

      c[i] = array1[i] + array2[i];

      System.out.println(ans);
    }
}

3 个答案:

答案 0 :(得分:1)

错了:

  • ans从未定义。
  • 您对c数组求和,但从不打印它们。

这是您应该做的:

public static void main(String[] args) {

    int array1[ ] = {1,2,3};
    int array2[ ] = {10,9,8};
    int[] c = new int[array1.length];

    int sumOfAll = 0;
    for(int i = 0; i<array1.length ; i++){
    c[i] = array1[i] + array2[i];
        sumOfAll += c[i];
        // if you just want the sum of each index.
        System.out.println("Sum each: " + c[i]);
    }
    // if you want to sum the total of array in c
    System.out.println("Sum of all: " + sumOfAll);

}

答案 1 :(得分:0)

您可以将数组元素迭代到单独的循环中,将每个数字求和成一个变量,然后打印出来,就像这样:

public class SumArray {

     public static void main(String[] args) {

            int array1[ ] = {1,2,3};
            int array2[ ] = {10,10,10,10};

            int sum = 0;

            for (int i : array2) {
                sum += i;
            }

            for (int i : array1) {
                sum += i;
            }

            System.out.println("result: " + sum);
        }

}

输出:

result: 46

或带有for和临时变量:

public class SumArray {

     public static void main(String[] args) {

            int array1[ ] = {1,2,3};
            int array2[ ] = {10,10,10,10};

            int sum = 0;
            for (int i = 0; i < array2.length; i++) {
                sum += array2[i];
            }

            for (int i = 0; i < array1.length; i++) {
                sum += array1[i];
            }

            System.out.println("result: " + sum);
        }

}

答案 2 :(得分:0)

    public static void main(String[] args) {

    int array1[ ] = {1,2,3};
    int array2[ ] = {10,9,8};
    int[] c = new int[array1.length];


    for(int i = 0; i<array1.length ; i++){

      c[i] = array1[i] + array2[i];

      System.out.println(c[i]);
    }
   }