考虑下面的代码:
#include <iostream> #include <cstdio> #include <cstring> using namespace std; template<class T> bool IsNaN(T t) { return t != t; } int main(int argc, char**argv) { double d1, d2; sscanf(argv[1], "%f", &d1); sscanf(argv[2], "%f", &d2); double dRes = d1/d2; cout << "dRes = " << dRes << "\n"; if(IsNaN(dRes)) cout << "Is NaN\n"; else cout << "Not NaN\n"; }
几个问题:
dRes = inf
。 但是我期待dRes = NaN
或类似的东西。 Floating exception
。 有什么不同? inf
? double
应该使用%lf
来读取,而不是%f
。 %f
将输入转换为32位float
,所以变量的前32位将填充一些无效数据,最后32位将被保留为垃圾。
是。 #include <limits>
, 则std::numeric_limits<double>::quiet_NaN()
。 一些编译器(例如gcc)也在<cmath>
提供NAN
宏 。
整数类型没有NaN或无穷大。 整数除以零将导致异常(SIGFPE) 。
#include <cmath>
,然后std::isinf(x)
。 使用std::isfinite(x)
来确保x
不是NaN或Infinity。