给定双精度数组,如何打印最接近零的整数?

How can I print the nearest integer to zero given an array of doubles?

我被这个作业问题卡住了:

Print out the double that is closest to 0, positive or negative.

我当前的代码是:

import java.util.Arrays;
import java.util.Scanner;

public class Code {

    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        // Read input for the test cases
        int N = scanner.nextInt();
        double[] doubles = new double[N];
        double closestToZero = N;
        for(int i = 0; i < N; i++) {
            doubles[i] = scanner.nextDouble();
        }

        // Your code here
        for(int a = 0; a < N; a++) {
            if (Math.abs(a) < 0) {
                closestToZero = a;
            }

                else if(Math.abs(a) == 0.0) {
                    closestToZero = a;
                }
                else {

                }
            }         
        System.out.println("The double closest to 0 is " + closestToZero);

    }
}

问题:即使答案不正确,代码仍打印出 0.0,错误的原因是什么?

最接近0的是绝对值最小的数。然后你只需要找到最小值。如果找到更小的数字,则更新 closestToZero。

import java.util.Arrays;
import java.util.Scanner;

public class Code {
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        // Read input for the test cases
        int N = scanner.nextInt();
        double[] doubles = new double[N];
        double closestToZero = Double.MAX_VALUE;
        for(int i = 0; i < N; i++) {
            doubles[i] = scanner.nextDouble();
        }

        // Your code here
        for(int a = 0; a < N; a++) {
            if (Math.abs(doubles[a]) < Math.abs(closestToZero)) {
                closestToZero = doubles[a];
            }
        }   
        
        System.out.println("The double closest to 0 is " + closestToZero );
    }
}

这是一种从 Double[] 数组中找到最接近零的值的更快、更有效的方法。

import java.util.Arrays;
import java.util.Scanner;

public class Whosebug_Tester {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter number of integers: ");
        int N = in.nextInt();
        double[] doubles = new double[N];
        for(int i = 0; i < N; i++) {
            doubles[i] = in.nextDouble();
        }
        double curr = 0;
        double near = doubles[0];
        // find the element nearest to zero
        for ( int i=0; i < doubles.length; i++ ){
            curr = doubles[i] * doubles[i];
            if ( curr <= (near * near) )  {
                near = doubles[i];
            }
        }
        System.out.println( near );
    }
}