Phrogz Phrogz - 2 months ago 24
C++ Question

Getting double result from abs(double) instead of int

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()
.

Answer

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.