fmin() Function
The fmin()
function returns the smaller of two numeric values. It ensures that if one of the arguments is not a number (NaN), the other valid number is returned. This behavior helps in obtaining a reliable minimum even when dealing with floating-point exceptional cases.
Syntax of fmin()
</>
Copy
double fmin(double x, double y);
float fminf(float x, float y);
long double fminl(long double x, long double y);
Parameters
Parameter | Description |
---|---|
x | First numeric value to compare. |
y | Second numeric value to compare. |
It is worth noting that if one of the arguments is a NaN, fmin()
returns the other value. This provides a way to gracefully handle cases where invalid numeric data might be encountered.
Examples for fmin()
Example 1: Finding the Minimum of Two Regular Double Values
This example demonstrates how to use fmin()
to compare two double values and print the smaller one.
Program
</>
Copy
#include <stdio.h>
#include <math.h>
int main() {
double a = 5.2;
double b = 3.7;
// Determine the minimum of a and b using fmin()
double minimum = fmin(a, b);
printf("The minimum value is: %.2f\n", minimum);
return 0;
}
Explanation:
- Two double variables
a
andb
are initialized with the values5.2
and3.7
respectively. - The
fmin()
function compares these values and returns the smaller one, which is stored in the variableminimum
. - The result is printed to the console using
printf()
.
Output:
The minimum value is: 3.70
Example 2: Handling NaN Values in Comparison
This example demonstrates the behavior of fmin()
when one of the operands is a NaN value.
Program
</>
Copy
#include <stdio.h>
#include <math.h>
int main() {
double validValue = 4.5;
double notANumber = NAN;
// fmin() returns the valid number when one argument is NaN
double minimum = fmin(validValue, notANumber);
printf("The minimum value when comparing a valid number and NaN is: %.2f\n", minimum);
return 0;
}
Explanation:
- A double variable
validValue
is initialized with a valid numeric value4.5
, whilenotANumber
is set toNAN
. - The
fmin()
function comparesvalidValue
withnotANumber
and returnsvalidValue
since it is the valid number. - The result is printed to the console using
printf()
, demonstrating thatfmin()
correctly handles NaN values.
Output:
The minimum value when comparing a valid number and NaN is: 4.50