fdim() Function in C
The fdim() function in C is part of the standard math library <math.h> and is used to compute the positive difference between two floating-point numbers. This function is particularly useful when we need to determine the non-negative difference between two given values. It returns the difference between two values if the first value is greater than the second; otherwise, it returns zero.
Syntax of fdim() in C
double fdim(double x, double y);
Parameters of fdim() in C
The fdim() function in C takes the following parameters:
- x: The first floating-point number.
- y: The second floating-point number.
Return Value of fdim() in C
The fdim() function returns the positive difference between x and y. If x is greater than y, it returns x - y; otherwise, it returns 0.
Examples of fdim() Function in C
The below examples demonstrate how we can use the fdim() function in C language.
Input:
double num1 = 5.5
double num2 = 3.2
Output:
The positive difference between 5.50 and 3.20 is: 2.30
Example 1
The below program demonstrates how to calculate the positive difference between two given numbers using the fdim() function in C.
// C Program to demonstrate the fdim() function
#include <math.h>
#include <stdio.h>
int main()
{
// initialize numbers
double x = 5.5, y = 3.2;
// calculate result by calling fdim() function
double result = fdim(x, y);
// Print the result
printf("The positive difference between %.2lf and "
"%.2lf is: %.2lf\n",
x, y, result);
return 0;
}
Output
The positive difference between 5.50 and 3.20 is: 2.30
Time Complexity: O(1)
Auxiliary Space: O(1)
Example 2
The following program demonstrates how to compute the positive difference for different data types in C.
// C program to demonstrate the fdim() function for
// different data types
#include <math.h>
#include <stdio.h>
int main()
{
// initialize numbers
double x1 = 5.5, y1 = 3.2;
float x2 = 6.5f, y2 = 3.2f;
long double x3 = 7.5l, y3 = 3.2l;
// fdim function for double
double result1 = fdim(x1, y1);
// fdimf function for float
float result2 = fdimf(x2, y2);
// fdiml function for long double
long double result3 = fdiml(x3, y3);
// Print the results
printf("The positive difference between %.2lf and "
"%.2lf is: %.2lf\n",
x1, y1, result1);
printf("The positive difference between %.2f and %.2f "
"is: %.2f\n",
x2, y2, result2);
printf("The positive difference between %.2Lf and "
"%.2Lf is: %.2Lf\n",
x3, y3, result3);
return 0;
}
Output
The positive difference between 5.50 and 3.20 is: 2.30 The positive difference between 6.50 and 3.20 is: 3.30 The positive difference between 7.50 and 3.20 is: 4.30
Time Complexity: O(1)
Auxiliary Space: O(1)
Note: The fdim() function is available in three variants: fdim() for double, fdimf() for float, and fdiml() for long double.