C stdlib abs syntax
int abs(int x);
In C, abs returns the magnitude of a number. For example, the absolute value of −6 is 6, and the absolute value of 0 is 0.
abs
#include <stdio.h>
#include <stdlib.h>
int main(void) {
printf("%.15g\n", (double) (abs(-3)));
}
3
int abs(int x);
| Input | An int. Include <stdlib.h>. |
|---|---|
| Result | An int. If the magnitude cannot be represented as an int, the behavior is undefined. Use fabs from <math.h> for a double. |
Note: C stdlib abs supports only integer.
A shop records a surplus as a positive count and a shortage as a negative count. The reconciliation report asks how many items differ in each case, regardless of direction.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, const char * argv[])
{
// Positive integer value
int n = abs(9);
printf("The absolute value of 9 is %d \n", n);
// Negative integer value
int x = abs(-6);
printf("The absolute value of -6 is %d \n", x);
return 0;
}
The absolute value of 9 is 9 The absolute value of -6 is 6
A scale reports deviations on either side of its reference weight. Find the size of each deviation while keeping the fractional part so small differences remain visible.
#include <stdio.h>
#include <math.h>
int main(int argc, const char * argv[])
{
// Positive floating point value
double n = fabs(9.3);
printf("The absolute value of 9.3 is %f \n", n);
// Negative floating point value
double x = fabs(-6.3);
printf("The absolute value of -6.3 is %f \n", x);
return 0;
}
The absolute value of 9.3 is 9.300000 The absolute value of -6.3 is 6.300000
A stocktake compares what the scanner found with what the inventory system expected. The report needs to distinguish a shortage, a surplus and an exact match before deciding whether to investigate.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int scanned = 47;
int expected = 52;
printf("%d\n", abs(scanned - expected));
return 0;
}
5
The scanner found 47 items against 52 on the manifest. The discrepancy is five items. Keep the signed difference separately to distinguish a shortage from a surplus.
A school library expects 48 loan chargers on its shelf after class. A student counts 45. The handover form has a separate field for the size of the discrepancy, whether the shelf is short or over.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int expected = 48, counted = 45;
printf("%d chargers", abs(counted - expected));
return 0;
}
3 chargers
The signed difference is minus three. Its magnitude gives the three chargers the next shift needs to account for.
A class logs the courtyard temperature at sunrise and again before lunch. The report asks how far apart the readings are, even when one is below freezing.
The two readings sit seven one-degree intervals apart on the same scale.
#include <stdlib.h>
#include <stdio.h>
int main(void) {
int sunrise = -3, midday = 4;
printf("%d °C\n", abs(midday - sunrise));
return 0;
}
7 °C
Reference: C numeric operations