为什么原始浮点值可以是-0.0?那是什么意思?
我可以取消该功能吗?
当我有:
float fl;
Run Code Online (Sandbox Code Playgroud)
然后fl == -0.0返回true,所以fl == 0.但是当我打印它时,它会打印出来-0.0.
我正在研究Java标准库(6)中compare(double,double)的实现.它写道:
public static int compare(double d1, double d2) {
if (d1 < d2)
return -1; // Neither val is NaN, thisVal is smaller
if (d1 > d2)
return 1; // Neither val is NaN, thisVal is larger
long thisBits = Double.doubleToLongBits(d1);
long anotherBits = Double.doubleToLongBits(d2);
return (thisBits == anotherBits ? 0 : // Values are equal
(thisBits < anotherBits ? -1 : // (-0.0, 0.0) or (!NaN, NaN)
1)); // (0.0, -0.0) or (NaN, !NaN)
}
Run Code Online (Sandbox Code Playgroud)
这个实现的优点是什么?
编辑:"优点"是一个(非常)糟糕的选择.我想知道它是如何工作的.
在Java中是否有任何内置方法,您可以在其中找到用户输入的类型,无论是正面还是负面等等?下面的代码不起作用.我试图找到一种方法来输入任何内置的方法,可以在if语句中执行它.
import java.util.Scanner;
public class Compare {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = input.nextInt();
if(number == int)
System.out.println("Number is natural and positive.");
}
}
Run Code Online (Sandbox Code Playgroud) 我一直试图弄清楚如何确定双值是否-0.0d.我搜索了一下这个问题并发现了一些不同的方法,但是我找到的所有线程至少都有几年的历史,而且似乎已经不再适用了.
这是我到目前为止所尝试的:
double x, y;
x = 0;
y = -0;
println(x == y);
println(Double.compare(x, y) == 0);
println(new Double(x).equals(new Double(y)));
println(Double.doubleToLongBits(x) == Double.doubleToLongBits(y));
println(Math.signum(x) == Math.signum(y));
Run Code Online (Sandbox Code Playgroud)
true不幸的是,所有这些都打印出来.
我需要区分0和-0的原因,如果你想知道,是因为我试图从用户输入解析double值,并在异常的情况下使用-0作为sentinel值.