'inf' 可以像 C++ 中的常规数值一样分配给变量吗

Can 'inf' be assigned to a variable like regular numeric values in c++

当我编写以下代码时,它没有导致运行时错误,而是输出了'inf'。现在,有没有办法将这个值 ('inf') 赋给一个变量,就像常规数值一样?如何检查除法是否产生 'inf'?

#include<iostream>    

int main(){
    double a = 1, b = 0;
    std::cout << a / b << endl;
    return 0;
}

看来我可以:

#include<iostream>

int main(){
    double a = 1, b = 0, c = 1/0.0;
    std::cout << a / b << endl;
    if (a / b == c) std::cout << "Yes you can.\n";

    return 0;
}

C++ 不要求实现支持无穷大或被零除。许多实现会,因为许多实现使用 IEEE 754 格式,即使它们不完全支持 IEEE 754 语义。

当你想使用无穷大作为一个值时(即你想在源代码中引用无穷大),你不应该通过除以零来生成它。相反,包括 <limits> 并使用 std::numeric_limits<T>::infinity() 并将 T 指定为 double.

Returns the special value "positive infinity", as represented by the floating-point type T. Only meaningful if std::numeric_limits< T >::has_infinity== true.

(您可能还会看到包含 <cmath> 并使用从 C 继承的 INFINITY 的代码。)

如果要检查 一个数是否有限,请包含 <cmath> 并使用 std::isfinite。请注意,具有无限值的计算往往最终会产生 NaNs,并且 std::isfinite(x) 通常比 !std::isinf(x) && !std::isnan(x).

更方便

如果您使用不安全的编译器标志的最后警告:如果您使用例如 GCC 的 -ffinite-math-only (included in -ffast-math) then std::isfinite does not work.