如何获得数组中前两个数字的平均值?

时间:2014-08-29 16:43:23

标签: java arrays methods double average

我无法弄清楚如何获得数组中前两个数字的平均值,然后是前三个数字。我在这些方面遇到错误。 average(numbers[0],numbers[1]));average(numbers[0],numbers[1],numbers[2]));这是我的代码。

public class NoVarargsTest{
    // calculate average
    public static double average(double[] numbers){
        double total = 0.0;
        // calculate total using the enhanced for statement
        for (double d : numbers){                
            total += d;
        }                          
        return (total / (double)numbers.length);
    }
    public static void main (String[] args) {
        double d1 = 10.0;
        double d2 = 20.0;
        double d3 = 30.0;
        double d4 = 40.0;

        double[] numbers= new double[4];
        numbers[0] = 10.0;
        numbers[1] = 20.0;
        numbers[2] = 30.0;
        numbers[3] = 40.0;

        if (args.length == 0)
            System.out.println("No Command Line arguments");
        else {

            System.out.println("You provided " + args.length
                    + " arguments");

            for (int i = 0; i < args.length; i++) {
                System.out.println("args[" + i + "]: "
                        + args[i]);
            }
        }

        System.out.printf("d1 = %.1f%nd2 = %.1f%nd3 = %.1f%nd4 = %.1f%n%n",numbers[0],numbers[1], numbers[2], numbers[3]);
        System.out.printf("Average of d1 and d2 is %.1f%n",
        average(numbers[0],numbers[1]));
        System.out.printf("Average of d1, d2 and d3 is %.1f%n",
        average(numbers[0],numbers[1],numbers[2]));
        System.out.printf("Average of d1, d2, d3 and d4 is %.1f%n",
        average(numbers)); 
    }

} // end class NoVarargsTest

3 个答案:

答案 0 :(得分:4)

如果要使用varargs,则必须将方法签名声明为:

public static double average(double... numbers){

numbers将成为您方法中的double[]

这由JLS §8.4.1: Formal Parameters指定。

答案 1 :(得分:2)

您的public static double average(double[] numbers)方法参数是double []数组,但您只需传递两个双精度值:average(numbers[0],numbers[1]));

要解决此问题,请将方法更改为public static double average(double... numbers)或传递数组:average(new double[] {numbers[0], numbers[1]})

答案 2 :(得分:0)

import java.util.Arrays;

public class NoVarargsTest
{
    // calculate average
    public static double average(double[] numbers)
    {

        double total = 0.0;
        // calculate total using the enhanced for statement
        for (double d : numbers)
        {
            total += d;
        }
        return total / (double)numbers.length;
    }

    // prints the wording around the array
    private static void driver(double[] numbers)
    {
        System.out.println("The average of " + Arrays.toString(numbers) + " is "+average(numbers));
    }

    public static void main(String[] args)
    {
        driver(new double[] {10});
        driver(new double[] {10, 20});
        driver(new double[] {10, 20, 30});
    }

} // end class VarargsTest