-3

How can I print the absolute value of a result?

Example:

  • |4-5| the result will be 1 (negative sign will be neglected)
  • |5-4| this also have the answer of 1 (positive value remains as positive value)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Bharath R
  • 19
  • 1

2 Answers2

1

I think you're asking for the abs() function from <stdlib.h>, which accepts an int and returns the absolute value (converting negative numbers to positive):

#include <stdlib.h>
#include <stdio.h>

int main() {
  printf("%i\n", abs(4-5));
  printf("%i\n", abs(5-4));
}

There is also fabs() which does the same for double values if you are working with floating point, and several other variants for wider data types.

You can of course alternatively implement a function like abs() yourself. A simple example (not intended to be optimal):

#include <stdio.h>

int my_abs(int v) {
  if (v >= 0) return v;
  else        return -v;
}

int main() {
  printf("%i\n", my_abs(4-5));
  printf("%i\n", my_abs(5-4));
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Dan Bonachea
  • 2,408
  • 5
  • 16
  • 31
0

It depends on what the 4,5 are .... are they floats or integers or something else? What encoding?

For an integer with two's complement you can:

#define abs(x) ((x<0)?(-x):x)

For data types with a sign bit instead it’s enough to clear the sign bit, so for example for a 32-bit integer in such encoding you can:

#define abs(x) (x&0x7FFFFFFF)

which is branchless. However, it is usual the int type is in two's complement in most environments, so you can not use this on them. However, floating point types are stored like this all the time, so they can be abs ed like this easily... just use pointers or union to get access to bit operations on them

float abs(float x)
{
    union
    {
        float f32;
        int i32;
    } u;

    u.f32 = x;
    u.i32 &= 0x7FFFFFFF;
    return u.f32;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Spektre
  • 49,595
  • 11
  • 110
  • 380
  • 1
    The macro shown above evaluates its argument multiple times, which can lead to subtle bugs if the passed argument expression includes side effects. It's safer and more robust to use a real function for that purpose. – Dan Bonachea Jan 08 '23 at 15:37
  • All modern processors you're likely to encounter use 2s complement encoding for `int`, so the second macro will basically never correctly provide the requested behavior for ints. – Dan Bonachea Jan 08 '23 at 15:43
  • @DanBonachea its highly unclear what the target datatype is ... it might be bigint, arbnum or whatever ... real function is a performance hit but yes if x is expression it could lead to problems however as implementation example its more than enough ... – Spektre Jan 08 '23 at 17:40
  • @Spektre Can you come to the chat room please ? – andre_lamothe Jan 18 '23 at 09:43