Use abs() or fabs() to Compute Absolute Value
In this step, you will learn how to compute absolute values in C using built-in functions abs()
for integers and fabs()
for floating-point numbers.
Understanding Absolute Value Functions
First, create a new file called absolute_value.c
in the ~/project
directory:
nano ~/project/absolute_value.c
Enter the following code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main() {
// Absolute value for integers
int intNumber = -42;
int intAbsolute = abs(intNumber);
// Absolute value for floating-point numbers
float floatNumber = -3.14;
float floatAbsolute = fabs(floatNumber);
// Displaying absolute values
printf("Integer: %d, Absolute Value: %d\n", intNumber, intAbsolute);
printf("Float: %f, Absolute Value: %f\n", floatNumber, floatAbsolute);
return 0;
}
Let's break down the code:
abs()
is used for integer absolute values (from <stdlib.h>
)
fabs()
is used for floating-point absolute values (from <math.h>
)
- Both functions return the non-negative magnitude of a number
Compile and Run the Program
Compile the program with the math library:
gcc ~/project/absolute_value.c -o ~/project/absolute_value -lm
Run the program:
~/project/absolute_value
Example output:
Integer: -42, Absolute Value: 42
Float: -3.140000, Absolute Value: 3.140000
Handling Different Number Types
Note the different header files and functions for integer and floating-point absolute values:
- For integers:
#include <stdlib.h>
and abs()
- For floating-point numbers:
#include <math.h>
and fabs()