What is the fmax() function in C++?

Overview

The `fmax()` function in C++ is used to return the larger number among two arguments (`x` and `y`) passed to the function.

The fmax() function is defined in the <cmath> header file.

Syntax

double fmax (double x, double y);
float fmax (float x, float y);
long double fmax (long double x, long double y);

Parameter value

The `fmax()` function takes two parameter values, `x` and `y`, which represent the first and second arguments of the function, respectively.

Return value

The `fmax()` function returns the larger value among the `x` and `y` values.

Example

#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double x = -2.05, y = -3.5, result;
result = fmax(x, y);
cout << "fmax(x, y) = " << result << endl;
return 0;
}

Code explanation

We can see from the code above that the `fmax()` function correctly returned `-2.05` as the larger value when compared to `-3.5`.

Using different types of argument

We can also use the `fmax()` function to compute for the larger number between arguments of different data types, such as a `double` and an `int`.
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
// using different argument types
double x = 89.1, result;
int y = 89;
result = fmax(x, y);
cout << "fmax(89.1, 89) = " << result << endl;
return 0;
}

Code explanation

We can see from the code above that the `fmax()` correctly returned the `double` (`89.1`) as the larger value when compared to the `int` (`89`).

Free Resources