How to get rid of minus sign from signed zero
I am using asin to calculate the angle. The code is as below :
double FindAngle(const double theValue)
{
开发者_如何学运维return asin(theValue);
}
FindAngle returns a -0.0 (signed zero), when the argument theValue = -0.0. Now, how do i get rid of the minus sign from the return value.
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.
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;
}
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)
double FindAngle(const double theValue)
{
return abs(asin(value));
}
You can use the following method.
value = Float.compare(value, -0.0f) == 0 ? 0.0f : value ;
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
).
精彩评论