[英]Best way to check if double equals negative infinity in C++
我發現了這個: http : //en.cppreference.com/w/cpp/numeric/math/isinf但它似乎檢查正無窮大。 我只想檢查一個值是否恰好等於負無窮大,或者換句話說是log(0)
謝謝你的回答! 根據下面的響應,這里有一些代碼顯示了什么有效。
#include <iostream>
#include <cmath>
#include <math.h>
using namespace std;
int main()
{
double c = std::log(0.0);
auto result = c == - INFINITY;
cout << result << endl;
return 0;
}
明顯和明確的怎么樣?
要檢查double x
是負無窮大,請檢查
x == -std::numeric_limits<double>::infinity()
如果x
是某些其他浮點類型,請根據需要更改double
。
std::numeric_limits
在標准頭<limits>
定義。 不要忘記將其添加到#include
列表中。
x == -1.0 / 0.0
如果if為x
為負無窮大,則此表達式的計算結果為true。
如果您願意包含cmath
,那么x == - INFINITY
更具可讀性。
假設浮點類型映射到IEEE 754格式,那么它們中的每一個都有自己的無窮大。 1.0 / 0.0
是double
無窮大。 INFINITY
的類型並不重要,因為“通常的算術轉換”將負責匹配==
的左側和右側的類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.