C++ 中的 fma() 函数

c++server side programmingprogramming更新于 2025/4/23 18:52:17

给定的任务是展示 C++ 中 fma() 函数的工作原理。在本文中,我们将研究此函数需要哪些参数以及它将返回哪些结果。

fma() 是 cmath 头文件的内置函数,它接受三个参数 x、y 和 z,并返回结果 x*y+z,而不会丢失任何中间结果的精度。

语法

float fma(float x, float y, float z);

double fma(double x, double y, double z);

long double fma(long double x, long double y, long double z);

参数

  • x − 要相乘的第一个元素。

  • y − 要与 x 相乘的第二个元素。

  • z − 将添加到 x 和 y 的结果中的第三个元素。

返回值

该函数返回 x*y+z 的准确结果。

示例

#include<iostream>
#include<cmath>
using namespace std;
int main() {
   double x = 2.1, y = 4.2, z = 9.4, answer;
   answer = fma(x, y, z);
   cout << x << " * " << y << " + " << z << " = " << answer << endl;
   return 0;
}

输出

如果我们运行上述代码,它将生成以下输出 −

2.1 * 4.2 + 9.4 = 18.22

示例

#include<bits/stdc++.h>
using namespace std; int main() {
   double a = 7.4, b = 9.3, c = 1.2;
   double ans = fma(a, b, c);
   cout << a << " * " << b << " + " << c << " = " << ans << endl;
   return 0;
}

输出

如果我们运行上述代码,它将生成以下输出 −

7.4 * 9.3 + 1.2 = 70.02

相关文章