考虑以下代码:
#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
,或者类似的东西,,
,并传递0和0时,我得到了一个Floating exception
。检查变量的值是否等于inf
的difference?
发布于 2010-11-04 17:44:30
在使用scanf()
double
时,应使用%lf
而不是%f
读取
%f
会将输入转换为32位float
,因此变量的前32位将被一些无效数据填充,而后32位将成为垃圾。#include <limits>
,then std::numeric_limits::quiet_NaN()
.一些编译器(如gcc)还为整数类型提供了NAN
macro in .#include <cmath>
,,然后是std::isinf(x)
。使用std::isfinite(x)
确保x
不是NaN或Infinity。发布于 2018-01-15 03:31:34
函数fpclassify
允许您检查所有特殊情况下的浮点值。
它在<math.h>
中作为一个宏出现在C99中,在<cmath>
中作为一个函数族,在float
、double
和long double
中使用std::fpclassify
这个重载名称,从C++11开始。
has首选项具有a nice example
发布于 2018-01-15 03:07:04
就像这样做:
if (dRes == +1.0/0.0 || dRes == -1.0/0.0) ... //+INF, -INF
if (dRes == +0.0/0.0 ) ... //+NaN; i.e. pow(2.0 ,16384.0)
https://stackoverflow.com/questions/4095337
复制相似问题