I have to check a float variable to determine the existence of a particular variable. Ideally it should have been a bool value or at least an int. Because of interface constraints and legacy code I am not able to change the data type to bool. So if I've to make a check, can I directly do it as shown below in the sample code:
我必须检查一个浮点变量来确定特定变量的存在。理想情况下,它应该是bool值或至少是int。由于接口约束和遗留代码,我无法将数据类型更改为bool。因此,如果我要进行检查,我可以直接执行它,如下面的示例代码所示:
void check(float f)
{
if (!f)
printf ("Zero val!\n");
else
printf ("Value exists!\n");
}
Would it be fool proof Or is there be a better way to do it, considering the fact how the value is stored in a float variable. Casting it to an short and checking is out of the game because : If the value is '1' it is stored as 0.9999998; casting it to a short would result in a '0' which is wrong.
它是否是万无一失的或者是否有更好的方法来做到这一点,考虑到值如何存储在浮点变量中。将它投射到一个简短的并且检查不在游戏中,因为:如果值为“1”,则存储为0.9999998;将它转换为短路会导致'0'错误。
P.S The code happens to be present in a Objective C file, but in the C format.
P.S代码恰好出现在Objective C文件中,但是采用C格式。
1 个解决方案
#1
1
What you have will work, with the slight caveat that it will detect both positive and negative zero as being zero values. That may or may not matter for your purposes. If you are running on a platform that doesn't have the default IEEE-754 behavior (like many embedded platforms), then denormals may also pass the !f
check, depending on how your compiler handles it. This is probably not a problem for you, but it's something to be aware of.
你所拥有的将会有所作为,但有一点需要注意,它会将正零和负零都检测为零值。这对您的目的可能有关,也可能无关紧要。如果您运行的平台没有默认的IEEE-754行为(如许多嵌入式平台),那么非正规也可以通过!f检查,具体取决于编译器处理它的方式。这对你来说可能不是问题,但需要注意的是。
If you must do this sort of thing in the future, it's probably a better idea to use "not a number" to indicate uninitialized float data, which you can then check for with either (f != f)
or isnan(f)
.
如果将来必须做这类事情,最好使用“非数字”来表示未初始化的浮点数据,然后可以用(f!= f)或isnan(f)检查。
#1
1
What you have will work, with the slight caveat that it will detect both positive and negative zero as being zero values. That may or may not matter for your purposes. If you are running on a platform that doesn't have the default IEEE-754 behavior (like many embedded platforms), then denormals may also pass the !f
check, depending on how your compiler handles it. This is probably not a problem for you, but it's something to be aware of.
你所拥有的将会有所作为,但有一点需要注意,它会将正零和负零都检测为零值。这对您的目的可能有关,也可能无关紧要。如果您运行的平台没有默认的IEEE-754行为(如许多嵌入式平台),那么非正规也可以通过!f检查,具体取决于编译器处理它的方式。这对你来说可能不是问题,但需要注意的是。
If you must do this sort of thing in the future, it's probably a better idea to use "not a number" to indicate uninitialized float data, which you can then check for with either (f != f)
or isnan(f)
.
如果将来必须做这类事情,最好使用“非数字”来表示未初始化的浮点数据,然后可以用(f!= f)或isnan(f)检查。