在一个 C++ 项目中,我看到了这个:
#include <cstdlib>
#include <cstdio>
static int isNegative(float arg)
{
char p[20]; // Assume 20 is enough
sprintf(p, "%f", arg);
return p[0] == '-';
}
int main()
{
printf("%d\n", isNegative(-1));
}
我听说sprintf()
可能有问题,因为它可能导致负号在写入 p
时消失。真的吗?或者这种方法是防弹的(但非常糟糕的做法)?
PS:忽略 -0
的极端情况。关注 sprintf()
。我知道存在更好的解决方案,但我只是对这个感到好奇。也欢迎来自 C 的人提供帮助。
最佳答案
您可以使用%+f
来确保输出符号(+
或-
)(尽管-
无论如何都会输出)。所以我认为它保证了正常的浮点值。
我唯一关心的是特殊值:inf 和 nan。所以我在输出中添加了打印 p
并做了一个实验。这是我在 gcc 6.3 中得到的:
printf("IsNegative: %d\n", isNegative(+1.0/+0.0));
printf("IsNegative: %d\n", isNegative(-1.0/+0.0));
printf("IsNegative: %d\n", isNegative(+0.0/+0.0));
printf("IsNegative: %d\n", isNegative(+0.0/-0.0));
printf("IsNegative: %d\n", isNegative(-0.0/+0.0));
printf("IsNegative: %d\n", isNegative(-0.0/-0.0));
结果:
p = +inf
IsNegative: 0
p = -inf
IsNegative: 1
p = -nan
IsNegative: 1
p = -nan
IsNegative: 1
p = -nan
IsNegative: 1
p = -nan
IsNegative: 1
只有 nan 的结果看起来很奇怪,除此之外该方法应该有效。
关于c++ - 检查 float 是否为负数的奇怪方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46189910/