有以下数组track
表示某些参数的增加。每行指的是5天:
[0] 5
[1] 10
[2] 12
[3] 11
[4] 7
[5] 6
[6] 10
[7] 15
[8] 16
我需要估算参数增加的平均时间。在这个例子中,从[0]到[2],从[5]到[8]。答案必须是:
Period 1 (from [0] to [2]) = 5+5+5 = 15 days.
Period 2 (from [5] to [8]) = 20 days
ANSWER = (15 + 20)/2 = 17.5 days
我写了以下代码。但它失败了因为curr
是>比最后一次迭代的track.length
。我该如何解决这个问题?
private double getAvgGrowingTime(double[] track)
{
List<Double> timeList = new ArrayList<Double>();
double temptime = 0.0;
boolean stop = false;
int curr = 1;
while (curr < track.length)
{
while (track[curr]>track[curr-1])
{
temptime += 5;
stop = false;
curr++;
}
if (!stop)
timeList.add(temptime);
temptime = 0.0;
stop = true;
curr++;
}
//...
}
答案 0 :(得分:1)
将内心改为:
while ( curr< track.length && track[curr]>track[curr-1])
{
temptime += 5;
stop = false;
curr++;
}
答案 1 :(得分:1)
两个问题:
要解决您的两个问题,您可以执行以下操作:
boolean first = true;
while (curr < track.length) {
while (curr < track.length && track[curr] > track[curr - 1]) {
if (curr == 1 && first) {
temptime += 5;
first = false;
}