跳到主要内容

C++ remainder() 函数

C++ 中的 remainder() 函数计算分子与分母(向最近的整数取整)的浮点余数。

remainder (x, y) = x - rquote * y

其中 rquotex/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); // 对于其他算术类型组合的额外重载

remainder() 函数接受两个参数,并返回 double、float 或 long double 类型的值。

这个函数定义在 <cmath> 头文件中。

remainder() 参数

  • x - 分子的值。
  • y - 分母的值。

remainder() 返回值

remainder() 函数返回 x/y 的浮点余数(向最近的整数取整)。

如果分母 y 为零,remainder() 返回 NaN(非数字)。

示例 1:C++ 中 remainder() 的工作原理

#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

示例 2:对不同类型参数使用 remainder() 函数

#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