Java 估计给定参数值增加时的平均时间
下面的数组Java 估计给定参数值增加时的平均时间,java,Java,下面的数组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 d
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++;
}
//...
}
private double getAvgGrowingTime(双[]轨道)
{
List timeList=new ArrayList();
双时间=0.0;
布尔停止=假;
int curr=1;
while(电流<轨道长度)
{
while(轨道[curr]>轨道[curr-1])
{
TENTIME+=5;
停止=错误;
curr++;
}
如果(!停止)
timeList.add(testime);
试探时间=0.0;
停止=真;
curr++;
}
//...
}
将内部代码更改为:
while ( curr< track.length && track[curr]>track[curr-1])
{
temptime += 5;
stop = false;
curr++;
}
while(currtrack[curr-1])
{
TENTIME+=5;
停止=错误;
curr++;
}
两个问题:
- 当你有5,10,15这样的数据时,你的输出将是你需要的10
- 您将使用上面的示例运行ArrayIndexOutOfBoundException,因为它将进入内部while循环,并且不会检查当前索引和跟踪中的元素数
boolean first = true;
while (curr < track.length) {
while (curr < track.length && track[curr] > track[curr - 1]) {
if (curr == 1 && first) {
temptime += 5;
first = false;
}
boolean first=true;
while(电流<轨道长度){
while(currtrack[curr-1]){
if(curr==1&&first){
TENTIME+=5;
第一个=假;
}
谢谢。(curr