C++ fmax()

C++ fmax() returns largest of the two values given as arguments.

Syntax

The syntax of C++ fmax() is

fmax(x, y)

where

ParameterDescription
xA double, float, long double, or integral type value.
yA double, float, long double, or integral type value.

Returns

The return value depends on the type of value passed for parameter x.

The return value of fmax(x) is

  • double if x is double.
  • float if x is float.
  • long double if x is long double.
  • Promoted if x and y are of different types. Promoted is long double if any of the argument is long double, else the Promoted is double.

The synopsis of fmax() function is

double fmax(double x, double y);
float fmax(float x, float y);
long double fmax(long double x, long double y);
Promoted fmax(Type1 x, Type2 y); // for combinations of integral types

fmax() is a function of cmath library. Include cmath library at the start of program, if using fmax() function.

Example

In this example, we read two values from user into variables x and y, and compute the largest of these two values using fmax() function.

C++ Program

#include <iostream>
#include<cmath>
using namespace std;

int main() {
    double x, y;
    cout << "Enter a value (x) : ";
    cin >> x;
    cout << "Enter a value (y) : ";
    cin >> y;
    
    double result = fmax(x, y);
    cout << "fmax(" << x << ", " << y << ") : " << result << endl;
}

Output

Enter a value (x) : 14.2
Enter a value (y) : 2.6
fmax(14.2, 2.6) : 14.2
Program ended with exit code: 0
Enter a value (x) : -5
Enter a value (y) : -99
fmax(-5, -99) : -5
Program ended with exit code: 0

If one of the values: x or y; is nan, then the other value is returned.

Enter a value (x) : nan
Enter a value (y) : 5
fmax(nan, 5) : 5
Program ended with exit code: 0

Conclusion

In this C++ Tutorial, we learned the syntax of C++ fmax(), and how to use this function to find the largest of two values, with the help of examples.