Java中的汽车加油问题.任何人都可以找出while循环条件中的任何错误吗? [英] Car fueling problem in java. Can anyone figure out any error in while loop condition?

查看:70
本文介绍了Java中的汽车加油问题.任何人都可以找出while循环条件中的任何错误吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import java.util.*;
import java.io.*;

public class CarFueling {
 static int compute_refills(int dist,int tank,int stops[],int n){
    
        int current_refills=0;
        int num_refills=0;
        int last_refill=0;
        while(current_refills<=n) {
             last_refill = current_refills;
            while ((current_refills <= n) && (stops[current_refills + 1] - stops[last_refill]) <= tank) {
                current_refills = current_refills + 1;
            }

            if (current_refills == last_refill)
                return -1;
            if (current_refills <= n)
                num_refills = num_refills + 1;


        }
        return num_refills;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int dist = scanner.nextInt();
        int tank = scanner.nextInt();
       int n = scanner.nextInt();
        int stops[] = new int[n*n*n];// to solve array index out of bound exception increase the size of the array
        for (int i = 0; i < n; i++) {
            stops[i] = scanner.nextInt();
        }

       System.out.println(compute_refills(dist,tank,stops,n));

    }
}

我认为while循环条件存在一些问题.
输入:
950400
4
200375550750
我的输出:
1
正确的输出:
2

I think there is some issue in my while loop condition.
Input:
950 400
4
200 375 550 750
my output:
1
correct output:
2

推荐答案

如果您看

(current_refills <= n) && (stops[current_refills + 1] ... )

部分,两件事:

  • current_refills< = n 对于 n-1 (n元素数组的最后一个元素,因为第一个元素的索引为0)都是正确的,并且 n (已在数组外部)
  • 然后 stops [current_refills + 1] 访问元素以后",这是这两种情况下最大值的1或2个元素
  • current_refills <= n is true for both n-1 (the last element of a n-element array, as the first one has index 0), and n (which is already outside the array)
  • then stops[current_refills + 1] accesses an element "later", which is 1 or 2 elements above the max for these two cases

但是实际上这是可行的,只是您可以在旅程的开头添加0,并在结尾添加 dist :

But actually this can work, just you could add 0 for the beginning of the trip and dist as the end:

int n = scanner.nextInt();
int stops[] = new int[n+2];
stops[0] = 0; // well, it is 0 already
stops[n+1] = dist;
for (int i = 1; i <= n; i++) {
    stops[i] = scanner.nextInt();
}

然后 compute_refills()可能正常工作(尽管我尚未检查).

Then compute_refills() may work correctly (though I haven't checked).

这篇关于Java中的汽车加油问题.任何人都可以找出while循环条件中的任何错误吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆