user3155478
user3155478

Reputation: 1055

How to get absolute value from double - c-language

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.

Upvotes: 77

Views: 173222

Answers (5)

Md.Rakibuz Sultan
Md.Rakibuz Sultan

Reputation: 919

  //use fabs()
  double sum_primary_diagonal=0;
  double sum_secondary_diagonal=0;
  double difference = fabs(sum_primary_diagonal - sum_secondary_diagonal);

Upvotes: 0

Firas Nomaan
Firas Nomaan

Reputation: 1

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

Upvotes: 0

herohuyongtao
herohuyongtao

Reputation: 50667

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

double d1 = fabs(-3.8951);

Upvotes: 127

haccks
haccks

Reputation: 106012

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);

Upvotes: 23

lurker
lurker

Reputation: 58244

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.

Upvotes: 6

Related Questions