我在使用subAverage类时遇到困难。使用main方法时,它似乎无法正常运行。基本上,subAverage对包含开始和结束索引在内的数组中的项目进行平均。但是,当我运行这个我得到

3
6
3


我什么时候应该得到

3
9
6


我究竟做错了什么?

public class Weight {

    int[] data;

    Weight(int[] init) {

        data = new int[init.length + 1];

        for (int j = 0; j < init.length; j++) {
            data[j] = init[j];
        }
    }

    int subAverage(int start, int end) {
        int sum = 0;
        for (int j = start; j <= end; j++) {
            sum = data[j] + sum;
        }
        return sum / (end - start + 1);
    }

    public static void main(String[] args) {
        int[] values = {1, 3, 5, 7, 9, 11};
        Weight june = new Weight(values);

        if (values.length % 2 == 0) {
            int firstHalf = june.subAverage(0, values.length / 2 - 1);
            int secondHalf = june.subAverage(values.length / 2, values.length);
            int difference = Math.abs(secondHalf - firstHalf);
            System.out.println(firstHalf);
            System.out.println(secondHalf);
            System.out.println(difference);
        }

        if (values.length % 2 == 1) {
            int firstHalf = june.subAverage(0, values.length / 2);
            int secondHalf = june.subAverage(values.length / 2, values.length);
            int difference = Math.abs(secondHalf - firstHalf);
            System.out.println(firstHalf);
            System.out.println(secondHalf);
            System.out.println(difference);
        }
    }
}

最佳答案

问题在于您的数据初始化代码[]

data = new int[init.length + 1];


它应该是

data = new int[init.length];


然后问题出在subAverage循环条件上

for (int j = start; j <= end; j++) {


它应该是

for (int j = start; j < end; j++) {


还有调用代码的另一个问题

int secondHalf = june.subAverage(values.length / 2, values.length);


它应该是

int secondHalf = june.subAverage(values.length / 2, values.length - 1);


希望这可以帮助。

10-06 06:52