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()
.
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.
Prior to C++17 abs
for floating points and for integrals were defined in different headers (cmath
and cstdlib
respectively).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With