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



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

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

最新更新