더블이 NAN과 동일인지 확인하기 위해 어떻게 테스트합니까?
문제
나는 자바에 더블이 있고 그것이 있는지 확인하고 싶습니다. NaN
. 이것을하는 가장 좋은 방법은 무엇입니까?
해결책
정적을 사용하십시오 Double.isNaN(double)
방법 또는 귀하의 Double
'에스 .isNaN()
방법.
// 1. static method
if (Double.isNaN(doubleValue)) {
...
}
// 2. object's method
if (doubleObject.isNaN()) {
...
}
단순히 수행 :
if (var == Double.NaN) {
...
}
~이다 충분치 않은 어떻게 NAN 및 부동 소수점 번호의 IEEE 표준 정의됩니다.
다른 팁
노력하다 Double.isNaN()
:
이 이중 값이 Nan-Number (NAN) 인 경우 True를 반환합니다. 그렇지 않으면 False.
참고double.isNaN()
] 비스듬한 복식에는 그들과 관련된 방법이 없기 때문에] 작동하지 않습니다.
값이 유한한지 확인하는 것도 고려할 수 있습니다. Double.isFinite(value)
. Java 8 이후 새로운 방법이 있습니다 Double
값이 NAN 및 무한대가 아닌 경우 한 번에 확인할 수있는 클래스.
/**
* Returns {@code true} if the argument is a finite floating-point
* value; returns {@code false} otherwise (for NaN and infinity
* arguments).
*
* @param d the {@code double} value to be tested
* @return {@code true} if the argument is a finite
* floating-point value, {@code false} otherwise.
* @since 1.8
*/
public static boolean isFinite(double d)
사용하여 NAN을 확인할 수 있습니다 var != var
. NaN
동일하지 않습니다 NaN
.
편집하다: 이것은 아마도 최악의 방법 일 것입니다. 혼란스럽고 가독성이 끔찍하며 전반적인 나쁜 연습.
초보자는 실제 사례가 필요합니다. 따라서 다음 코드를 사용해보십시오.
public class Not_a_Number {
public static void main(String[] args) {
// TODO Auto-generated method stub
String message = "0.0/0.0 is NaN.\nsimilarly Math.sqrt(-1) is NaN.";
String dottedLine = "------------------------------------------------";
Double numerator = -2.0;
Double denominator = -2.0;
while (denominator <= 1) {
Double x = numerator/denominator;
Double y = new Double (x);
boolean z = y.isNaN();
System.out.println("y = " + y);
System.out.println("z = " + z);
if (z == true){
System.out.println(message);
}
else {
System.out.println("Hi, everyone");
}
numerator = numerator + 1;
denominator = denominator +1;
System.out.println(dottedLine);
} // end of while
} // end of main
} // end of class
아래 코드 스 니펫은 원시 유형 보유 NAN을 평가하는 데 도움이됩니다.
double dbl = Double.NaN;
Double.valueOf(dbl).isNaN() ? true : false;
제휴하지 않습니다 StackOverflow