我正在尝试制作一个将最接近的数字打印为零而不使用数组的程序,但我尝试打印最小的数字,因为它将是最接近的数字为零,但是当其中一个数字为负数时,这将不起作用

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

最佳答案

如果要查找最接近零的数字,则应检查输入的最小绝对值:

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


请注意,我们需要在不等式的两边都使用绝对值。

关于java - 如何在循环中将最接近的数字设为零,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57211627/

10-14 12:31
查看更多