C ++中的restder()函数计算分子/分母的浮点余数(四舍五入到最接近的值)。
remainder (x, y) = x - rquote * y
其中,rquote是x/y的结果,四舍五入到最接近的整数值(一半情况下四舍五入到偶数)。
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
restder()函数接受两个参数,并返回double,float或long double类型的值。
此函数在<cmath>头文件中定义。
x -分子的值。
y -分母的值。
restder()函数返回x/y的浮点余数(四舍五入到最接近的值)。
如果分母y为零,则remainder()返回NaN(不是数字)。
#include <iostream> #include <cmath> using namespace std; int main() { double x = 7.5, y = 2.1; double result = remainder(x, y); cout << "余数 " << x << "/" << y << " = " << result << endl; x = -17.50, y=2.0; result = remainder(x, y); cout << "余数 " << x << "/" << y << " = " << result << endl; y=0; result = remainder(x, y); cout << "余数 " << x << "/" << y << " = " << result << endl; return 0; }
运行该程序时,输出为:
余数 7.5/2.1 = -0.9 余数 -17.5/2 = 0.5 余数 -17.5/0 = -nan
#include <iostream> #include <cmath> using namespace std; int main() { int x = 5; double y = 2.13, result; result = remainder(x, y); cout << "余数 " << x << "/" << y << " = " << result << endl; return 0; }
运行该程序时,输出为:
余数 5/2.13 = 0.74