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.
Edit:
You can of course alternatively implement a function like abs()
yourself. 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:
depends on what the 4,5
are .... are they floats or integers or something else? what encoding?
for integer with two's complement you can:
#define abs(x) ((x<0)?(-x):x)
For datatypes with sign bit instead its enough to clear the sign bit so for example for 32 bit int in such encoding you can:
#define abs(x) (x&0x7FFFFFFF)
which is brunchless however is usual the int
type is in two's complement on 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;
}