Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting double result from abs(double) instead of int

Tags:

c++

I need to calculate the absolute value of a difference of two double values and have a double result. Instead, I'm getting an int.

#include <typeinfo>
// ...
printf(
    "a:%s b:%s delta:%s abs:%s\n",
    typeid(a).name(),
    typeid(b).name(),
    typeid(a - b).name(),
    typeid(abs(a - b)).name()
);
// Prints: a:d b:d delta:d abs:i

If the result of the subtraction is already a double, why is abs not using the double abs (double x); signature? Indeed, how can it be returning an integer at all? Most importantly, how do I force it to return a double?

In case it makes a difference, a and b are actually myData.m_lat and otherData.latitude().

like image 411
Phrogz Avatar asked Sep 28 '16 15:09

Phrogz


2 Answers

To avoid clashes with unintentionally imported C standard library headers, use std::abs instead. That's the C++ version, and is heavily overloaded, as you already know.

Otherwise use fabs from the C standard library.

like image 105
Bathsheba Avatar answered Oct 09 '22 17:10

Bathsheba


Prior to C++17 abs for floating points and for integrals were defined in different headers (cmath and cstdlib respectively).

like image 32
krzaq Avatar answered Oct 09 '22 19:10

krzaq