首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

无效的变量值?该怎么处理

2012-09-08 
无效的变量值?程序在计算过程中出现了无效的变量值“-1.#IND00000000”,有没有方法检测这个变量是否有效呢?

无效的变量值?
程序在计算过程中出现了无效的变量值“-1.#IND00000000”,有没有方法检测这个变量是否有效呢?量是double类型。这个变
  程序暂不能从逻辑上去修改出现这个问题的代码,主要是要解决当出现了这样的值,怎么去检测?好做特殊处理,这个double类型变量功能上也没有限制。

[解决办法]
看下面的红字部分。出现“-1.#IND00000000”,意味着你用一个数(而且是负数)除以0了。检查你的代码看看是否存在这样的情况。

Debugging 1.#IND, 1.#INF, nan, and inf

If your operation would generate a larger positive number than could be stored in a double, the operation will return 1.#INF on Windows or inf on Linux. Similarly your code will return -1.#INF or -inf if the result would be a negative number too large to store in a double. Dividing a positive number by zero produces a positive infinity and dividing a negative number by zero produces a negative infinity. Example code at the end of this page will demonstrate some operations that produce infinities.

Some operations don't make mathematical sense, such as taking the square root of a negative number. (Yes, this operation makes sense in the context of complex numbers, but a double represents a real number and so there is no double to represent the result.) The same is true for logarithms of negative numbers. Both sqrt(-1.0) and log(-1.0) would return a NaN, the generic term for a "number" that is "not a number". Windows displays a NaN as -1.#IND ("IND" for "indeterminate") while Linux displays nan. Other operations that would return a NaN include 0/0, 0*∞, and ∞/∞. See the sample code below for examples.

In short, if you get 1.#INF or inf, look for overflow or division by zero. If you get 1.#IND or nan, look for illegal operations. Maybe you simply have a bug. If it's more subtle and you have something that is difficult to compute, see Avoiding Overflow, Underflow, and Loss of Precision. That article gives tricks for computing results that have intermediate steps overflow if computed directly.
[解决办法]
首先我觉得这样的问题出现,肯定与计算的过程有关,最好的办法是检测代码,找出潜在的问题。
至于楼主说的问题,下面的方案可供参考,不确定完全正确;
我们知道在C++中有类似于这样的常量,DBL_MAX,所以任何定义的double变量 x ,必定符合
-DBL_MAX<=x<=DBL_MAX
而同时也发现使用IND和double便量作比较操作总是返回false,所以可以使用下面的参考方法

double x = myFun(); // 可能产生IND的函数
if(x>=-DBL_MAX){
// 所有正常double都满足此条件
}else{
// 出现错误时会到这里
}

// 此方法在VS2010下试验过,其它环境不确定

热点排行