为什么要使用abs()或fabs()而不是条件求反? [英] Why use abs() or fabs() instead of conditional negation?

查看:60
本文介绍了为什么要使用abs()或fabs()而不是条件求反?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C/C ++中,为什么不使用以下代码就使用 abs() fabs()查找变量的绝对值?

In C/C++, why should one use abs() or fabs() to find the absolute value of a variable without using the following code?

int absoluteValue = value < 0 ? -value : value;

它与较低级别的较少指令有关吗?

Does it have something to do with fewer instructions at lower level?

推荐答案

您提出的条件abs"不等同于 std :: abs (或 fabs )有关浮点数,请参见例如

The "conditional abs" you propose is not equivalent to std::abs (or fabs) for floating point numbers, see e.g.

#include <iostream>
#include <cmath>

int main () {
    double d = -0.0;
    double a = d < 0 ? -d : d;
    std::cout << d << ' ' << a << ' ' << std::abs(d);
}

输出:

-0 -0 0

给出 -0.0 0.0 表示相同的实数"0",根据使用结果的方式,此差异可能或可能无关紧要.但是,IEEE754指定的abs函数要求结果的符号位必须为0,这将禁止结果 -0.0 .我个人认为用于计算某些绝对值"的任何内容都应与此行为相符.

Given -0.0 and 0.0 represent the same real number '0', this difference may or may not matter, depending on how the result is used. However, the abs function as specified by IEEE754 mandates the signbit of the result to be 0, which would forbid the result -0.0. I personally think anything used to calculate some "absolute value" should match this behavior.

对于整数,这两个变量在运行时和行为上都是等效的.(实时示例)

For integers, both variants will be equivalent both in runtime and behavior. (Live example)

但是,由于众所周知 std :: abs (或适合的C语言等效项)是正确的且易于阅读,因此您应该始终偏爱这些.

But as std::abs (or the fitting C equivalents) are known to be correct and easier to read, you should just always prefer those.

这篇关于为什么要使用abs()或fabs()而不是条件求反?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆