对任意数量的整数求和的 Java 方法

2022-01-09 00:00:00 sum java

我需要编写一个 java 方法 sumAll(),它接受任意数量的整数并返回它们的总和.

I need to write a java method sumAll() which takes any number of integers and returns their sum.

sumAll(1,2,3) returns 6
sumAll() returns 0
sumAll(20) returns 20

我不知道该怎么做.

推荐答案

你需要:

public int sumAll(int...numbers){

    int result = 0;
    for(int i = 0 ; i < numbers.length; i++) {
        result += numbers[i];
    } 
    return result;
}

然后调用该方法并为其提供所需数量的 int 值:

Then call the method and give it as many int values as you need:

int result = sumAll(1,4,6,3,5,393,4,5);//.....
System.out.println(result);

相关文章