让printf忽略零值上的负号

问题描述 投票:2回答:5

我正在尝试编写一个(大部分)* C程序,该程序对数值结果进行排序并消除重复项。结果存储为STRUCTS,其中包含一个字符串,一个整数和4个双精度值。双打与确定两个结果是否重复有关。

为此,我使用4个双精度点将字符串sprintf达到一定的精度,即。

    #define PRECISION 5
sprintf(hashString, "%.*lf %.*lf %.*lf %.*lf", PRECISION, result.v1, PRECISION, result.v2, PRECISION, result.v3, PRECISION, result.v4);

然后,我将其用作tr1::unordered_map<string, ResultType>的哈希键。然后程序检查哈希表是否已经包含该键的条目,如果是,则结果是重复的并且可以丢弃。否则,它将被添加到哈希表中。

问题是,有时我的值之一会被sprintf从-10E-9舍入为零;结果,该字符串将包含“ -0.00000”而不是“ 0.00000”。尽管表示相同的结果,但这两个值显然将生成不同的哈希键。

sprintf甚至C语言中是否内置了某些可以让我处理的东西?我想出了一些解决方法(请参阅下面的文章)-但是,如果有内置的东西,我宁愿使用它。

*该程序是用C编写的,因为这是我最熟悉的语言,但是最终我将使用g ++进行编译,以便使用unordered_map。

我已经提出以下解决方法。但是A)我希望有一个内置的解决方案,B)我对atof或浮点数学没有很深入的了解,因此我不确定条件if(doubleRepresentation == 0.0)是否总是会在适当的时候触发。

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    #define PRECISION 5
    #define ACCURACY 10E-6
    double getRidOfNegZeros (double number)
    {

            char someNumAsStr[PRECISION + 3]; // +3 accounts for a possible minus sign, the leading 0 or 1, and the decimal place.
            sprintf(someNumAsStr, "%.*lf", PRECISION, number);

            double doubleRepresentation = atof(someNumAsStr);
            if((doubleRepresentation < ACCURACY) && (doubleRepresentation > -ACCURACY))
            {
                    doubleRepresentation = 0.0;
            }

            return doubleRepresentation;
    }

    int main()
    {
            printf("Enter a number: \n");
            double somenum;
            scanf("%lf",&somenum);

            printf("The new representation of double \"%.*lf\" is \"%.*lf\"\n", PRECISION, somenum, PRECISION, getRidOfNegZeros(somenum));
            return 0;
    }
c++ printf zero negative-number
5个回答
0
投票
#include <string>

#define PRECISION 5
#define LIMIT 5e-6

std::string string_rep (double x) {
   char buf[32];
   double xtrunc = ((x > -LIMIT) && (x < LIMIT)) ? 0.0 : x;
   std::sprintf (buf, "%.*f", PRECISION, xtrunc);
   return std::string(buf);
}

std::string make_key (double x, double y, double z, double w) {
   std::string strx = string_rep (x);
   std::string stry = string_rep (y);
   std::string strz = string_rep (z);
   std::string strw = string_rep (w);
   return strx + " " + stry + " " + strz + " " + strw;
}

2
投票

而不是sprintf()将双精度型转换为大字符串并将其用作映射中的键,为什么不将您的结构放入映射中呢?如果您只为结构编写一个小于运算符,并考虑要用作键的浮点值,则可以轻松完成此操作。像这样的东西:

bool operator <(const MyStruct &lhs, const MyStruct &rhs)
{
    return lhs.v1 < rhs.v1 ||
        (lhs.v1 == rhs.v1 && lhs.v2 < rhs.v2); // ...
}

然后您可以将tr1::unordered_map<string, ResultType>替换为std::map<ResultType>,并避免整个字符串打印业务。如果需要,可以在比较函数中添加一些epsilon,以便稳定地对几乎相同的数字进行排序。


1
投票

如果知道只关心0.00001的差异(基于PRECISION的定义),则可以先将值四舍五入为整数。这样的事情可能会起作用:

#include <math.h>
#include <stdio.h>

#define SCALE 1e5 // instead of PRECISION 5
sprintf(hashString, "%d %d %d %d",
    (int)round(result.v1 * SCALE),
    (int)round(result.v2 * SCALE),
    (int)round(result.v3 * SCALE),
    (int)round(result.v4 * SCALE));

这也需要对浮点值的大小进行限制。您不想溢出整数值。

[您也可以绕过字符串格式,并像其他人所建议的那样,作为结构级哈希的一部分简单地进行舍入计算。


0
投票

如果仅出于散列双精度值的目的而使用此函数,则不必费心将它们转换为字符串,只需直接对双精度值进行哈希即可。任何有价值的哈希库都可以哈希任意二进制二进制数据。

如果出于某种奇怪的原因,您的哈希库仅支持以null终止的C字符串,请打印出double值的原始字节:

// Alias the double value as a byte array
unsigned char *d = (unsigned char *)&result.v1;
// Prefer snprintf to sprintf!
spnrintf(hashString, hashStringLength, "%02x%02x%02x%02x%02x%02x%02x%02x",
         d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7]);
// ...and so on for each double value

这可确保不相等的值一定会被赋予不相等的字符串。


0
投票

也许实现了一个实用函数,将值四舍五入/捕捉到正零。使用类似于printf样式格式语法的精确数字计数。

// Prevent display of -0 values by snapping to positive zero
// \a_number original number
// \a_precisionCount number of digits of decimal precision eg. 2 for #.##, 0 for whole integer. Default 0 (whole integer number.)
// \returns number rounded to positive zero if result would have produced -0.00 for precision.
template <class Real>
Real PosZero(const Real& a_number, const int a_precisionCount = 0)
{
    Real precisionValue = Real(0.5) * pow(Real(0.10), Real(a_precisionCount));
    if( (a_number > -abs(precisionValue)) && (a_number < abs(precisionValue)) )
    {
        return +0.0;
    }
    return a_number;
}

测试:

f32 value = -0.049f;
int precision = 4; // Test precision from param
printf("%.0f, %.2f, %.*f", PosZero(value), PosZero(value,2), precision, PosZero(value,precision));

测试输出:

"0, -0.05, -0.0490"

这是为希望避免格式化字符串中的负零的人们提供的通用解决方案。不特定于原始海报使用的创建哈希值。

© www.soinside.com 2019 - 2024. All rights reserved.