fmax() Function
The fmax()
function in C returns the larger of two floating-point values. It is a convenient utility for comparing two numbers and determining the maximum value, even when one of the values is a NaN. If a NaN is encountered, the valid numeric value is returned, ensuring reliable comparisons in various scenarios.
Syntax of fmax()
double fmax(double x, double y);
float fmaxf(float x, float y);
long double fmaxl(long double x, long double y);
Parameters
Parameter | Description |
---|---|
x, y | Values among which the function selects the maximum. |
The fmax()
function is particularly useful when you want to obtain the highest value from two floating-point numbers. It ensures that if one of the arguments is a NaN, the other valid number is chosen. This behavior provides a robust mechanism for comparisons in mathematical computations.
Examples for fmax()
Example 1: Comparing Two Positive Floating-Point Numbers
This example demonstrates the use of fmax()
to compare two positive numbers and determine the larger value.
Program
#include <stdio.h>
#include <math.h>
int main() {
double a = 3.5, b = 7.2;
double maxVal = fmax(a, b);
printf("Maximum value: %f\n", maxVal);
return 0;
}
Explanation:
- The program declares two double variables,
a
andb
, with positive floating-point values. - The
fmax()
function compares the two values and returns the larger one. - The resulting maximum value is printed using
printf()
.
Program Output:
Maximum value: 7.200000
Example 2: Handling NaN Values in fmax() Comparison
This example shows how fmax()
behaves when one of the values is a NaN. The function returns the valid numeric value, ensuring a meaningful result.
Program
#include <stdio.h>
#include <math.h>
int main() {
double a = 5.0;
double b = NAN;
double maxVal = fmax(a, b);
printf("Maximum value when one argument is NaN: %f\n", maxVal);
return 0;
}
Explanation:
- Variable
a
is assigned a valid floating-point value, whileb
is set to NaN. - The
fmax()
function compares the two values. - Since one value is NaN, the function returns the valid number
a
. - The resulting value is printed using
printf()
.
Program Output:
Maximum value when one argument is NaN: 5.000000
Example 3: Comparing Two Negative Floating-Point Numbers
This example demonstrates how fmax()
selects the larger (or less negative) value when comparing two negative numbers.
Program
#include <stdio.h>
#include <math.h>
int main() {
double a = -3.5, b = -7.2;
double maxVal = fmax(a, b);
printf("Maximum value: %f\n", maxVal);
return 0;
}
Explanation:
- Two negative floating-point values are declared in variables
a
andb
. - The
fmax()
function compares the two values and returns the less negative (i.e., larger) value. - The result is then printed using
printf()
.
Program Output:
Maximum value: -3.500000