C++ 中的 remainder() 函数计算 numerator/denominator 的浮点余数(四舍五入到最接近的整数)。
remainder (x, y) = x - rquote * y
其中 rquote
是 x/y
的结果,该结果四舍五入到最接近的整数(对于恰好在中间的情况,四舍五入到偶数)。
remainder() 原型 [自 C++ 11 标准起]
double remainder(double x, double y); float remainder(float x, float y); long double remainder(long double x, long double y); double remainder(Type1 x, Type2 y); // Additional overloads for other combinations of arithmetic types
remainder() 函数接受两个参数,并返回 double、float 或 long double 类型的值。
此函数定义在 <cmath> 头文件中。
remainder() 参数
- x - 被除数的值。
- y - 除数的值。
remainder() 返回值
remainder() 函数返回 x/y 的浮点余数(四舍五入到最接近的整数)。
如果除数 y 为零,remainder() 返回 NaN
(非数字)。
示例 1:remainder() 在 C++ 中如何工作?
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double x = 7.5, y = 2.1;
double result = remainder(x, y);
cout << "Remainder of " << x << "/" << y << " = " << result << endl;
x = -17.50, y=2.0;
result = remainder(x, y);
cout << "Remainder of " << x << "/" << y << " = " << result << endl;
y=0;
result = remainder(x, y);
cout << "Remainder of " << x << "/" << y << " = " << result << endl;
return 0;
}
运行程序后,输出将是
Remainder of 7.5/2.1 = -0.9 Remainder of -17.5/2 = 0.5 Remainder of -17.5/0 = -nan
示例 2:不同类型参数的 remainder() 函数
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int x = 5;
double y = 2.13, result;
result = remainder(x, y);
cout << "Remainder of " << x << "/" << y << " = " << result << endl;
return 0;
}
运行程序后,输出将是
Remainder of 5/2.13 = 0.74
另请阅读