how to get the closest number to zero in a loop

Mody Mada :

I am trying to make a program that print the closest number to zero without using arrays I tried to print the minimum number as it will be the closest number to zero but this doesnot work when one of the numbers is negative

 public static void main(String[] args) {
    Scanner in = new Scanner(System.in);

    int n = in.nextInt();
    int t = 0;
    int min = Integer.MAX_VALUE;
    for (int i = 0; i < n; i++) {
        t = in.nextInt();
        if (t < min) {
            min = t;
        }
    }
    System.out.println(min);
}
Tim Biegeleisen :

If you want to find the number closest to zero, then you should be checking for the smallest absolute value of the input:

int min = Integer.MAX_VALUE;
for (int i=0; i < n; i++) {
    t = in.nextInt();
    if (Math.abs(t) < Math.abs(min)) {
        min = t;
    }
}

Note carefully that we need to use the absolute value on both sides of the inequality.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=329163&siteId=1