Search code examples
javaarraysmathdouble

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


I am stuck on this homework problem:

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

My current code is:

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);

    }
}

Issue: The code keeps printing out 0.0 even though it is the incorrect answer, What would be the cause for the error?


Solution

  • Closest to 0 is the smallest number in absolute value. Then you only have to find the minimum. Update closestToZero if a smaller number is found.

    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 );
        }
    }