gpt4 book ai didi

java - 数组 - 平均

转载 作者:行者123 更新时间:2023-11-29 09:43:50 30 4
gpt4 key购买 nike

我在使用 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[] 初始化代码上

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);

希望这对您有所帮助。

关于java - 数组 - 平均,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21832400/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com