69

I want the absolute-value from a negative double - and I thought the abs-function was as easy to use as in java - but NOT!

It seems that the abs-function returns an int because I have the value 3.8951 and the output is 3.000000

double d1 = abs(-3.8951);
printf("d1: ...%lf", d1);

How can I fix this problem? That is - I want the absolute value of a double.

herohuyongtao
  • 49,413
  • 29
  • 133
  • 174
user3155478
  • 975
  • 1
  • 10
  • 16
  • 12
    Did you try `fabs(-3.8951)`? `man abs` says "compute the absolute value of an integer" and `fabs(3)` is cross-referenced in the "SEE ALSO". Never assume that things work the same way across different languages. Especially since Java has classes and can overload methods, but C does not. – lurker Jan 06 '14 at 18:07
  • @mbratch - thanks!!!!!!!!!!!!!!! I will consider this in the future – user3155478 Jan 06 '14 at 18:10
  • abs is only implemented for integer in C. That's why the answers are all recommending you use fabs, which is the floating-point equivalent. – outis nihil Jan 06 '14 at 18:11
  • " absolute-value from a negative double" is easy: `-x`. ;-) – chux - Reinstate Monica Feb 09 '21 at 17:33
  • If this question was asked in 2023, it could possibly get -15 downvotes + duplicate + close. :P – Rohan Bari Jul 30 '23 at 06:19

5 Answers5

115

Use fabs() (in math.h) to get absolute-value for double:

double d1 = fabs(-3.8951);
herohuyongtao
  • 49,413
  • 29
  • 133
  • 174
22

Use fabs instead of abs to find absolute value of double (or float) data types. Include the <math.h> header for fabs function.

double d1 = fabs(-3.8951);
haccks
  • 104,019
  • 25
  • 176
  • 264
5

It's worth noting that Java can overload a method such as abs so that it works with an integer or a double. In C, overloading doesn't exist, so you need different functions for integer versus double.

lurker
  • 56,987
  • 9
  • 69
  • 103
0

I have found that using cabs(double), cabsf(float), cabsl(long double), __cabsf(float), __cabs(double), __cabsf(long double) is the solution

barbsan
  • 3,418
  • 11
  • 21
  • 28
  • 5
    These `cabs`-like functions are for complex numbers, so it may be out of scope of this question. It would be good to [edit] your post and include this information (and maybe explain what's the difference between `cabs` and `__cabs`) – barbsan Nov 19 '18 at 13:58
0
  //use fabs()
  double sum_primary_diagonal=0;
  double sum_secondary_diagonal=0;
  double difference = fabs(sum_primary_diagonal - sum_secondary_diagonal);
Md.Rakibuz Sultan
  • 759
  • 1
  • 8
  • 13