nak*_*iya 20 c++ linux floating-point g++
请考虑以下代码:
#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";
}
Run Code Online (Sandbox Code Playgroud)
几个问题:
dRes = inf
.但我期待dRes = NaN
或类似的东西.Floating exception
.有什么不同?inf
?ken*_*ytm 30
使用scanf()
double
时应使用%lf
,而不是%f
.%f
将输入转换为32位float
,因此变量的前32位将填充一些无效数据,最后32位将保留为垃圾.
是.#include <limits>
,然后std::numeric_limits<double>::quiet_NaN()
.一些编译器(例如gcc)也提供了NAN
宏<cmath>
.
整数类型没有NaN或无穷大.整数除以零将导致异常(SIGFPE).
#include <cmath>
那么std::isinf(x)
.使用std::isfinite(x)
,以确保x
不NAN或无穷大.