Fdim
定义于头文件 <cmath>
中。
描述
返回 x
和 y
之间的正差,即如果 x > y
,则返回 x - y
,否则(即如果 x <= y
)返回 +0
。该库为所有 cv-unqualified 浮点类型提供了 std::fdim
的重载作为参数 x
和 y
的类型。
声明
- C++23
- C++11
// 1)
constexpr /* floating-point-type */
fdim ( /* floating-point-type */ x,
/* floating-point-type */ y );
// 2)
constexpr float fdimf( float x, float y );
// 3)
constexpr long double fdiml( long double x, long double y );
// 4)
template< class Arithmetic1, class Arithmetic2 >
constexpr /* common-floating-point-type */ fdim( Arithmetic1 x, Arithmetic2 y );
// 1)
float fdim ( float x, float y );
// 2)
double fdim ( double x, double y );
// 3)
long double fdim ( long double x, long double y );
// 4)
float fdimf( float x, float y );
// 5)
long double fdiml( long double x, long double y );
// 6)
template< class Arithmetic1, class Arithmetic2 >
/* common-floating-point-type */ fdim( Arithmetic1 x, Arithmetic2 y );
参数
x
,y
- 浮点或整数值
返回值
如果成功,返回 x
和 y
之间的正差。
如果因溢出导致范围错误,则返回 +HUGE_VAL
、+HUGE_VALF
或 +HUGE_VALL
。
如果因下溢导致范围错误,则返回正确的值(四舍五入后)。
错误处理
错误按 math_errhandling 中指定的方式报告。
如果实现支持 IEEE 浮点运算(IEC 60559)
如果任一参数是 NaN,返回 NaN
备注
等同于 std::fmax(x - y, 0)
,除了 NaN 处理要求。
不需要严格按照 附加重载 提供附加重载。它们只需要足以确保对于它们的第一个参数 num1
和第二个参数 num2
如果 num1
或 num2
的类型是 long double,则
std::fdim(num1, num2)
具有与以下相同的效果:
std::fdim(static_cast<long double>(num1), static_cast<long double>(num2))
.
否则,如果 num1
和/或 num2
的类型是 double 或整数类型,则
std::fdim(num1, num2)
具有与以下相同的效果:
std::fdim(static_cast<double>(num1), static_cast<double>(num2))
.
否则,如果 num1
或 num2
的类型为 float,则
std::fdim(num1, num2)
具有与以下相同的效果:
std::fdim(static_cast<float>(num1), static_cast<float>(num2))
。 (直到 C++23)
如果 num1
和 num2
具有算术类型,则
std::fdim(num1, num2)
具有与以下相同的效果:
std::fdim(static_cast</* common-floating-point-type */>(num1), static_cast</* common-floating-point-type */>(num2))
其中 /* common-floating-point-type */ 是 num1
和 num2
类型之间具有最大浮点转换等级和最大浮点转换子等级的浮点类型,整数类型参数被认为具有与 double 相同的浮点转换等级。
如果不存在具有最高等级和子等级的浮点类型,则重载决议不会从提供的重载中产生可用的候选。
示例
#include <cerrno>
#include <cfenv>
#include <cmath>
#include <cstring>
#include <iostream>
#ifndef __GNUC__
#pragma STDC FENV_ACCESS ON
#endif
int main()
{
std::cout
<< "fdim(4, 1) = "
<< std::fdim(4, 1) << '\n'
<< "fdim(1, 4) = "
<< std::fdim(1, 4) << '\n'
<< "fdim(4,-1) = "
<< std::fdim(4, -1) << '\n'
<< "fdim(1,-4) = "
<< std::fdim(1, -4) << '\n';
// error handling
errno = 0;
std::feclearexcept(FE_ALL_EXCEPT);
std::cout
<< "fdim(1e308, -1e308) = "
<< std::fdim(1e308, -1e308) << '\n';
if (errno == ERANGE)
std::cout
<< "errno == ERANGE: "
<< std::strerror(errno) << '\n';
if (std::fetestexcept(FE_OVERFLOW))
std::cout
<< "FE_OVERFLOW raised\n";
}
fdim(4, 1) = 3
fdim(1, 4) = 0
fdim(4,-1) = 5
fdim(1,-4) = 5
fdim(1e308, -1e308) = inf
errno == ERANGE: Numerical result out of range
FE_OVERFLOW raised