给定双精度数组,如何打印最接近零的整数?
我被这个家庭作业问题困住了:
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,即使它是错误的答案,错误的原因是什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最接近0的是绝对值最小的数。那么你只需要找到最小值即可。如果找到较小的数字,则更新closestToZero。
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.
这是从 Double[] 数组中查找最接近零的值的更快、更有效的方法。
here is a faster and more efficient way of finding the closent value to zero from a Double[] array.