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)
CodePudding user response:
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));
}
CodePudding user response:
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;
}