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)
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)
On
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;
}
I think you're asking for the
abs()function from<stdlib.h>, which accepts anintand returns the absolute value (converting negative numbers to positive):There is also
fabs()which does the same fordoublevalues 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):