代码之家  ›  专栏  ›  技术社区  ›  gsamaras a Data Head

检查浮点数是否为负数的奇怪方法

  •  0
  • gsamaras a Data Head  · 技术社区  · 7 年前

    在一个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 . 专注于 . 我知道存在更好的解决方案,但我只是对这一个好奇。也欢迎来自C的人提供帮助。

    2 回复  |  直到 7 年前
        1
  •  2
  •   Mikhail    7 年前

    您可以使用 %+f 确保标志( + - )是输出(尽管 -

    我唯一关心的是特殊值:inf和nan。所以我添加了打印 p

    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
    

    这个结果对于南来说很奇怪,除了这个方法应该有效之外。

        2
  •  1
  •   Krishna Prasad P    2 年前

    应用指定负值小于0且正值大于0的基本数学规则。

    #include <cstdio>
    
    static int isNegative(float arg)
    {
        return ((static_cast<int>(arg+1) > 0) ? 0 :1);
    }
    
    int main()
    {
        printf("%d\n", isNegative(-1));
        printf("%d\n", isNegative(-0.046));
        printf("%d\n", isNegative(3));
        printf("%d\n", isNegative(0.253));
    }
    

    1
    1
    0
    0