How to calculate the absolute value in the C language?
In C language, you can use the abs function to calculate the absolute value of an integer.
#include <stdio.h>
#include <stdlib.h>
int main() {
int num = -5;
int absolute = abs(num);
printf("The absolute value of %d is %d\n", num, absolute);
return 0;
}
The output results are:
The absolute value of -5 is 5
The fabs function can be used to calculate the absolute value of a floating point number.
#include <stdio.h>
#include <math.h>
int main() {
float num = -3.14;
float absolute = fabs(num);
printf("The absolute value of %.2f is %.2f\n", num, absolute);
return 0;
}
The output result is:
The absolute value of -3.14 is 3.14