简体   繁体   English

如何摆脱签名零的减号

[英]How to get rid of minus sign from signed zero

I am using asin to calculate the angle. 我用asin来计算角度。 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. 当参数theValue = -0.0时,FindAngle返回-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. 如果您只想将-0转换为0并保持其他未触及,请进行比较。

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. 包括<cmath>并在返回值上使用abs函数,如果你想要所有结果都是正数,或者检查你的返回值是否等于-0.0并获取它的abs值,就这种情况而言。

abs function (c++ reference) abs函数(c ++参考)

您可以使用以下方法。

 value = Float.compare(value, -0.0f) == 0 ? 0.0f : value ;
double FindAngle(const double theValue)
{
    return abs(asin(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.) (在这种情况下,如上面FacundoJ所提出的那样, 向其添加0.0 - 实际上可以解决它。假设你的算术符合IEEE 754,那就是。)

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. 另一方面,如果你的问题是printf("%f", x)产生-0.000000 (或类似的类似格式说明符),那么只添加0.0是不够的:你将得到任何小的相同输出,但负面,价值。

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() : 作为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 ). 这会根据需要产生“ +0000.0000 ”(当然,对于x = -0.50001E-4 “- -0000.0001 ”)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM