余数
定义于头文件 <cmath>
中。
描述
此函数计算的除法运算 x / y
的 IEEE 浮点余数精确地等于 x - quo * y
,其中 quo
是最接近精确值 x / y
的整数值。当 |quo-x/y| = ½
时,quo
值被选择为偶数。
与 std::fmod 不同,返回值的符号不保证与 x
相同。
如果返回值为零,则其符号与 x
相同。
声明
- C++23
- C++11
// 1)
constexpr /* floating-point-type */
remainder ( /* floating-point-type */ x,
/* floating-point-type */ y );
// 2)
constexpr float remainderf( float x, float y );
// 3)
constexpr long double remainderl( long double x, long double y );
// 4)
template< class Arithmetic1, class Arithmetic2 >
/* common-floating-point-type */
constexpr remainder( Arithmetic1 x, Arithmetic2 y );
// 1)
float remainder ( float x, float y );
// 2)
double remainder ( double x, double y );
// 3)
long double remainder ( long double x, long double y );
// 4)
float remainderf( float x, float y );
// 5)
long double remainderl( long double x, long double y );
// 6)
template< class Arithmetic1, class Arithmetic2 >
/* common-floating-point-type */
remainder( Arithmetic1 x, Arithmetic2 y );
参数
x
, y
- 浮点或整数值
返回值
如果成功,返回除法 x / y
的 IEEE 浮点余数,如上所述。
如果发生域错误,返回一个实现定义的值(如果支持,则为 NaN)
如果由于下溢发生范围错误,则返回正确结果。
如果 y
为零,但未发生域错误,则返回零。
错误处理
错误按 math_errhandling 中指定的方式报告。
如果 y
为零,可能会发生域错误。
如果实现支持 IEEE 浮点运算(IEC 60559),
当前的舍入模式无效。FE_INEXACT 从不引发,结果始终是精确的。
- 如果
x
是 ±∞ 且y
不是 NaN,返回 NaN 并引发 FE_INVALID - 如果
y
是 ±0 且x
不是 NaN,返回 NaN 并引发 FE_INVALID - 如果任一参数是 NaN,返回 NaN
示例
#include <cfenv>
#include <cmath>
#include <iostream>
// #pragma STDC FENV_ACCESS ON
int main()
{
std::cout
<< "remainder(+5.1, +3.0) = "
<< std::remainder(5.1, 3) << '\n'
<< "remainder(-5.1, +3.0) = "
<< std::remainder(-5.1, 3) << '\n'
<< "remainder(+5.1, -3.0) = "
<< std::remainder(5.1, -3) << '\n'
<< "remainder(-5.1, -3.0) = "
<< std::remainder(-5.1, -3) << '\n';
// special values
std::cout
<< "remainder(-0.0, 1.0) = "
<< std::remainder(-0.0, 1) << '\n'
<< "remainder(5.1, Inf) = "
<< std::remainder(5.1, INFINITY) << '\n';
// error handling
std::feclearexcept(FE_ALL_EXCEPT);
std::cout
<< "remainder(+5.1, 0) = "
<< std::remainder(5.1, 0) << '\n';
if (fetestexcept(FE_INVALID))
std::cout
<< "FE_INVALID raised\n";
}
remainder(+5.1, +3.0) = -0.9
remainder(-5.1, +3.0) = 0.9
remainder(+5.1, -3.0) = -0.9
remainder(-5.1, -3.0) = 0.9
remainder(-0.0, 1.0) = -0
remainder(5.1, Inf) = 5.1
remainder(+5.1, 0) = -nan
FE_INVALID raised