How to get rid of minus sign from signed zero

前端 未结 6 403
心在旅途
心在旅途 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:41

    include <cmath> and use the abs function on your return value, if you want all results to be positive, or check if your return value is equal to -0.0 and take the abs value of it, for just that case.

    abs function (c++ reference)

    0 讨论(0)
  • 2021-01-13 05:47
    double FindAngle(const double theValue)
    {
        return abs(asin(value));
    }
    
    0 讨论(0)
  • 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).

    0 讨论(0)
  • 2021-01-13 06:00

    You can do the following:

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

    I had the same problem and that worked for me.

    0 讨论(0)
  • 2021-01-13 06:04

    You can use the following method.

     value = Float.compare(value, -0.0f) == 0 ? 0.0f : value ;
    
    0 讨论(0)
  • 2021-01-13 06:06

    If you just want to convert -0 to 0 and leave other untouched, just do a comparison.

    double FindAngle(double value) {
        double res = asin(value);
        if (res == 0.0) res = 0.0;
        return res;
    }
    
    0 讨论(0)
提交回复
热议问题