How to get rid of minus sign from signed zero

前端 未结 6 402
心在旅途
心在旅途 2021-01-13 05:19

I am using asin to calculate the angle. The code is as below :

double FindAngle(const double theValue)
{
     return asin(theValue);
}

Find

6条回答
  •  说谎
    说谎 (楼主)
    2021-01-13 05:58

    Are you sure that signed zero is your problem? (In this case, adding 0.0 to it—as proposed by FacundoJ above—would in fact solve it. Provided your arithmetic conforms to IEEE 754, that is.)

    If, on the other hand, your problem is that printf("%f", x) produces -0.000000 (or similar for a similar format specifier), then just adding 0.0 is not enough: you will get the same output for any small, but negative, value.

    In this case some actual programming is needed (at least I know of no better solution). I used something like this the other day:

    int snrfmt(char *s, const char *format, double x)
    {
        int n, m;
        char z[32];
    
        n = sprintf(s, format, x);
        m = sprintf(z, format, -DBL_MIN);
        if (n == m && strcmp(s, z) == 0)
            n = sprintf(s, format, 0.0);
        return n;
    }
    

    as a kind-of replacement for sprintf():

    double x = -1.23E-45;
    char nr[80];
    
    (void)snrfmt(buf, "%#+010.4f", x);
    puts(nr);
    

    This produces "+0000.0000" as desired (but of course "-0000.0001" for x = -0.50001E-4).

提交回复
热议问题