gpt4 book ai didi

java - 平均值和数组(Codingbat : scoresAverage)

转载 作者:行者123 更新时间:2023-12-01 18:50:51 25 4
gpt4 key购买 nike

我正在codingbat.com 上解决Java 问题,并且在这个问题上停止了,scoresAverage。由于练习描述有点复杂,我就直接粘贴在这里:

Given an array of scores, compute the int average of the first half and the second half, and return whichever is larger. We'll say that the second half begins at index length/2. The array length will be at least 2. To practice decomposition, write a separate helper method
int average(int[] scores, int start, int end) { which computes the average of the elements between indexes start..end. Call your helper method twice to implement scoresAverage(). Write your helper method after your scoresAverage() method in the JavaBat text area. Normally you would compute averages with doubles, but here we use ints so the expected results are exact.

到目前为止,我的代码没有返回任何错误,但它返回的数字不正确。谁能帮我这个?我的代码尝试如下:

public int scoresAverage(int[] scores) {
int mid = scores.length/2;

int average1 = average(scores, 0, mid);
int average2 = average(scores, mid, scores.length);

return Math.max(average1,average2);
}


public int average(int[] scores, int start, int end){
int sum = 0;
for (int i=start; i<end; i++){
sum += scores[i];
}
return sum/(scores.length);
}

最佳答案

sum/scores.length 将对所有数字的总和进行平均;您希望 sum/(end - start) 对数字子集的总和进行平均

关于java - 平均值和数组(Codingbat : scoresAverage),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15973245/

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