如何检查双变量中的inf(和|或)NaN [英] How to check for inf (and | or) NaN in a double variable
问题描述
请考虑以下代码:
#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";
}
几个问题:
- 当我传递0和0作为参数时,它会输出
dRes = inf
。但我希望dRes = NaN
或类似的东西。 - NaN是否代表双变量?对于这个问题,任何变量?
- 当我将d1,d2,dRes的数据类型改为int并传递0和0时,得到一个
/ code>。
- 如何检查变量的值是否等于
inf
?
- When I pass 0 and 0 as arguments, it outputs
dRes = inf
. But I was expectingdRes = NaN
or something like that. - Is NaN representable in double variables? For that matter, any variable?
- When I changed the data type of d1,d2,dRes to int and passed 0 and 0, I got a
Floating exception
. What is the difference? - How to check if a variable's value is equal to
inf
?
推荐答案
-
double
请使用%lf
,而不是%f
读取。%f
将输入转换为32位float
,因此您的变量的前32位将被填充带有一些无效数据,最后32位将作为垃圾留下。
double
should be read using%lf
, not%f
.%f
will convert the input into a 32-bitfloat
, so the first 32 bits of your variables will be filled with some invalid data, and the last 32 bits will be left as garbage.
是的。 #include< limits>
,然后 std :: numeric_limits< double> :: quiet_NaN()
。某些编译器(例如gcc)还提供 NAN code>< cmath>
Yes. #include <limits>
, then std::numeric_limits<double>::quiet_NaN()
. Some compilers (e.g. gcc) also provides the NAN
macro in <cmath>
.
整数类型的NaN或无穷大。整数除以将导致异常(SIGFPE)。
There is no NaN or infinity for integer types. Divide-by-zero for integer will cause an exception (SIGFPE).
#include< cmath>
,然后 std :: isinf(x)
。使用 std :: isfinite(x)
确保 x
不是NaN或无限。
#include <cmath>
, then std::isinf(x)
. Use std::isfinite(x)
to ensure x
is not NaN or Infinity.
这篇关于如何检查双变量中的inf(和|或)NaN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!