C library function -fabs()
Description
C Library Functionsdouble fabs(double x)Returns a floating-point numberxabsolute value.
fabs()is the C standard library<math.h>A function used to calculate the absolute value of a number. This function is very useful in mathematical operations and ensures a non-negative representation of the value.
Note:The fabs() function can be used with arguments of type double, float, and long double. If you need to calculate the absolute value of an integer, you should useabs()function.
Declaration
Below is the declaration of the fabs() function.
#include <math.h> double fabs(double x); float fabsf(float x); long double fabsl(long double x);
Parameter
x: a floating-point number.
Return Value
- return
xThe absolute value, i.e., ifxgreater than or equal to 0, then returnx; ifxless than 0, then return-x。
Example
The following example demonstrates the usage of the fabs() function.
Example
#include <math.h>
int main ()
{
int a, b;
a = 1234;
b = -344;
printf("The absolute value of %d is %lf\n", a, fabs(a));
printf("The absolute value of %d is %lf\n", b, fabs(b));
return(0);
}
Let us compile and run the above program, this will produce the following result:
1234 的绝对值是 1234.000000 -344 的绝对值是 344.000000
Handling the absolute values of multiple values
The following example demonstrates how to handle the absolute value calculation of multiple values:
Example
#include <math.h>
int main() {
double values[] = {-5.67, 8.9, -10.0, 0.0};
int num_values = sizeof(values) / sizeof(values[0]);
for (int i = 0; i < num_values; i++) {
double x = values[i];
double result = fabs(x);
printf("fabs(%f) = %f\n", x, result);
}
return 0;
}
Let us compile and run the above program, this will produce the following result:
fabs(-5.670000) = 5.670000 fabs(8.900000) = 8.900000 fabs(-10.000000) = 10.000000 fabs(0.000000) = 0.000000
Code explanation
- Define an array containing multiple floating-point numbers
values。 - Usage
forLoop through each value, callfabs(x)function to perform the absolute value calculation. - Print the absolute value calculation result for each value.
Use Case
fabs()The function has a wide range of applications in many contexts, including but not limited to:
- Ensuring a non-negative representation of values, used in the processing of physical quantities such as distance and speed.
- Calculate error values or deviations.
- Process values in mathematical calculations.
Summary
fabs()The function is used to calculate the absolute value of a number and is one of the commonly used tools in mathematical operations. Through reasonable usefabs(), it can ensure a non-negative representation of values and achieve accurate numerical calculations in scientific computing, engineering applications, and numerical processing.