写一个简单的数学程序

时间:2014-02-10 12:57:54

标签: java

任何人都可以帮助我完成这项java工作;我遇到了困难

编写程序将以下标记加在一起并找到平均值: 45,56,34,89 输出所有标记,总(总和)和平均标记。

到目前为止,我已经做到了。

public class Average {
    public static void main (String args []) {
        int Average;
        Average = (45 + 56 + 34 + 89) / 4;

        System.out.printin(45 + 56 + 34 + 89) / 4;
    }
}

有人可以帮我完成这个吗?

1 个答案:

答案 0 :(得分:2)

会是这样的:

public class Average {
    // Can contain any number of `int` numbers
    static int[] numbers = {45, 56, 34, 88};

    public static void main(String[] args) {
        // Create an instance of `Average` class to call non `static` method 

        final double result = new Average().calculateAverage(numbers);
        System.out.println("result = " + result);

    }

    double calculateAverage(int[] array) {
        int count = 0; // count of numbers
        int sum = 0;   // count of sum all of numbers 
        for (int currentNumber : array) {
            count++;
            sum += currentNumber;
        }
        // You need to divide by double value to not lost decimal part,
        // so cast `count` to `double`.
        return sum / (double) count;
    }
}

结果是:

result = 55.75