简体   繁体   English

如何从 C++ 代码中删除负零?

[英]How to remove negative Zeros from c++ codes?

How to remove "negative zero" in c/c++?如何删除c/c++中的“负零”? I am trying this-我正在尝试这个-

#define isEq(a, b) ((abs(a-b)<EPS) ? 1 : 0)
#define NegZero(x) (x = isEq(x, -0.0) ? 0 : x)

Is it okay and safe?安全吗? or is there any other easy and safe way?或者有其他简单安全的方法吗? Specially for contest coding.专门用于比赛编码。 please help....请帮忙....

With the code you posted in your comments, your approach seems correct: your answer is a negative number that is very close to zero, and because you're rounding it to three digits (using printf("... %.3lf ...", ...) ), it looks like -0.000 .使用您在评论中发布的代码,您的方法似乎是正确的:您的答案是一个非常接近于零的负数,并且因为您将其四舍五入为三位数(使用printf("... %.3lf ...", ...) ),它看起来像-0.000 Your approach (check if it's close to 0.0 using abs(a - b) < epsilon ; if it is, use 0.0 , otherwise use the value itself) is mostly correct, except for the issue that macros aren't exactly a good fit.您的方法(检查它是否接近0.0使用abs(a - b) < epsilon ;如果是,使用0.0 ,否则使用值本身)大部分是正确的,除了宏不完全适合的问题。

Rather than writing而不是写作

printf("(%.3lf,%.3lf)\n", I1.x, I1.y);

I would suggest using something like我建议使用类似的东西

printf(
    "(%.3lf,%.3lf)\n",
    NegZero(I1.x),
    NegZero(I1.y)
);

and define (although I'd pick different names)并定义(虽然我会选择不同的名字)

static inline bool isEq(double x, double y) {
    return abs(x, y) < EPS;
}

static inline NegZero(double x) {
    if (isEq(x, 0.0)) {
        return 0.0;
    } else {
        return x;
    }
}

(The reason for the confused comments is that there actually is something called negative zero in IEEE floating point arithmetic. If that were the case, the suggested solutions would have worked.) (混淆评论的原因是在 IEEE 浮点运算中实际上有一种叫做负零的东西。如果是这种情况,建议的解决方案就会奏效。)

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

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