一个float或double变量除了表示数值之外,其实它还存在另外两种状态即 NaN
和 Inf
. 如果使用这两种状态来计算时,将会产生不可预计的结果. 所以在使用浮点型变量前,应该对变量的状态进行判断,并做对应处理.<br />
在 Qt
对于这种两种状态判断可以分别使用 qIsNaN
和 qIsInf
来判断.<br />在C库 math.h
里, 可以用使用 isnan(double)
和 isinf(double)
来判断.<br />下面举例说明:
double f1 = 1.0;
double f2 = -1.0;
double f3 = 0.0;
double f4 = f1 / f3; // INF
double f5 = f2 / f3; // INF
double f6 = f3 / f3; // NaN
double f7 = -f3 / f3; // NaN
double f8 = f4 / f4;
double f9 = f5 / f5;
double fa = -f4 / f4;
double fb = f1 / f6;
double fc = f2 / f6;
double fd = f6 / f1;
double fe = f6 / f2;
double ff = f7 / f7;
double fg = f4 / f3;
double fh = f5 / f3;
qDebug("%s(%s)[%d] NaN:\n f1(%d)\n f2(%d)\n f3(%d)\n f4(%d)\n f5(%d)\n f6(%d)\n f7(%d)\n f8(%d)\n f9(%d)\n fa(%d)\n fb(%d)\n fc(%d)\n fd(%d)\n fe(%d)\n ff(%d)\n fg(%d)\n fh(%d)\n", __FILE__, __func__, __LINE__,
qIsNaN(f1), qIsNaN(f2), qIsNaN(f3), qIsNaN(f4), qIsNaN(f5), qIsNaN(f6), qIsNaN(f7), qIsNaN(f8), qIsNaN(f9), qIsNaN(fa), qIsNaN(fb), qIsNaN(fc),
qIsNaN(fd), qIsNaN(fe), qIsNaN(ff), qIsNaN(fg), qIsNaN(fh));
qDebug("%s(%s)[%d] Inf:\n f1(%d)\n f2(%d)\n f3(%d)\n f4(%d)\n f5(%d)\n f6(%d)\n f7(%d)\n f8(%d)\n f9(%d)\n fa(%d)\n fb(%d)\n fc(%d)\n fd(%d)\n fe(%d)\n ff(%d)\n fg(%d)\n fh(%d)\n", __FILE__, __func__, __LINE__,
qIsInf(f1), qIsInf(f2), qIsInf(f3), qIsInf(f4), qIsInf(f5), qIsInf(f6), qIsInf(f7), qIsInf(f8), qIsInf(f9), qIsInf(fa), qIsInf(fb), qIsInf(fc),
qIsInf(fd), qIsInf(fe), qIsInf(ff), qIsInf(fg), qIsInf(fh));
规律:
-
0
除以0
,得到一个NaN
值 -
Inf
除以一个非0
值,得到一个NaN
值 - 任何数据除以一个
Inf
, 得到一个NaN
值 - 一个非
0
数据除以0
,将得到一个Inf
值