c++ - 检查 float 是否为负数的奇怪方法

标签 c++ c function floating-point printf

在一个 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/

相关文章:

c++ - 现在从 C++11 中的 "return"语句到 "switch"是错误的吗?

c - 指向结构体的指针的二维数组(动态)

JavaScript 切换函数

python - python3上的简单书店程序

c++ - 使用按位运算生成子序列的逻辑是什么?

c++ - 插入顺序 std::map

c++ - std::bind 类内部,事件系统的一般概念

c - 如果使用 lseek(),为什么文件描述符上的 read() 会失败?

c - 将人类可读的大小(k、M、G、T)解析为 C 中的字节

python - 无法从Python函数内部访问全局变量