In this C++ tutorial, you will learn how to find the smallest of two given values using fmin() function of cmath, with syntax and examples.

C++ fmin()

C++ fmin() returns smallest of two values given as arguments

Syntax

The syntax of C++ fmin() is

fmin(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 fmin(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 fmin() function is

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

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

ADVERTISEMENT

Example

In this example, we read two values from user into variables x and y, and compute the smallest of these two values using fmin() 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 = fmin(x, y);
    cout << "fmin(" << x << ", " << y << ") : " << result << endl;
}

Output

Enter a value (x) : 14.2
Enter a value (y) : 2.6
fmin(14.2, 2.6) : 2.6
Program ended with exit code: 0
Enter a value (x) : -5
Enter a value (y) : -99
fmin(-5, -99) : -99
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
fmin(nan, 5) : 5
Program ended with exit code: 0

Conclusion

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