In this C++ tutorial, you will learn how to compute the value of (x*y + z) using fma() function of cmath, with syntax and examples.

C++ fma()

C++ fma(x, y, z) computes and returns the value of (x*y + z).

Syntax

The syntax of C++ fma() is

fma(x, y, z)

where

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

Returns

The return value depends on the type of value passed for parameters x, y and z. The return value of fma() is

  • double if the arguments are double.
  • float if the arguments are float.
  • long double if the arguments are long double.
  • Promoted to the higher of the given arguments for integral type arguments.

The synopsis of fma() function is

double fma(double x, double y, double z);
float fma(float x, float y, float z);
long double fma(long double x, long double y, long double z);
Promoted fma(Type1 x, Type2 y, Type z); // for integral type argument values

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

ADVERTISEMENT

Example

In this example, we read three values from user into x, y and z, and find the value of x*y+z using fma() function.

C++ Program

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

int main() {
    double x, y, z;
    cout << "Enter x : ";
    cin >> x;
    cout << "Enter y : ";
    cin >> y;
    cout << "Enter z : ";
    cin >> z;

    double result = fma(x, y, z);
    cout << "fma(x, y, z) : " << result << endl;
}

Output

Enter x : 5
Enter y : 2
Enter z : 3
fma(x, y, z) : 13
Program ended with exit code: 0

Run#2

If any of the arguments is inf, then fma() returns inf.

Enter x : inf
Enter y : 10
Enter z : 2
fma(x, y, z) : inf
Program ended with exit code: 0

Run#3

If any of the arguments is -inf, then fma() returns -inf.

Enter x : -inf
Enter y : 2
Enter z : 3
fma(x, y, z) : -inf
Program ended with exit code: 0

Conclusion

In this C++ Tutorial, we learned the syntax of C++ fma(), and how to use this function, with the help of examples.