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()

</>
Copy
double fmax(double x, double y);
float  fmaxf(float x, float y);
long double fmaxl(long double x, long double y);

Parameters

ParameterDescription
x, yValues 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

</>
Copy
#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:

  1. The program declares two double variables, a and b, with positive floating-point values.
  2. The fmax() function compares the two values and returns the larger one.
  3. 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

</>
Copy
#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:

  1. Variable a is assigned a valid floating-point value, while b is set to NaN.
  2. The fmax() function compares the two values.
  3. Since one value is NaN, the function returns the valid number a.
  4. 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

</>
Copy
#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:

  1. Two negative floating-point values are declared in variables a and b.
  2. The fmax() function compares the two values and returns the less negative (i.e., larger) value.
  3. The result is then printed using printf().

Program Output:

Maximum value: -3.500000