跳到主要内容

C++ fmod() 浮点数取余函数

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

fmod (x, y) = x - tquote * y

其中 tquote 是 x/y 的截断结果,即(向零取整)。

fmod() 函数原型 [C++ 11 标准起]

double fmod(double x, double y);
float fmod(float x, float y);
long double fmod(long double x, long double y);
double fmod(Type1 x, Type2 y); // 对于其他算术类型组合的额外重载

fmod() 函数接受两个参数,并返回 double、float 或 long double 类型的值。这个函数定义在 <cmath> 头文件中。

fmod() 参数

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

fmod() 返回值

fmod() 函数返回 x/y 的浮点余数。如果分母 y 为零,fmod() 返回 NaN(非数字)。

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

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
double x = 7.5, y = 2.1;
double result = fmod(x, y);
cout << x << "/" << y << " 的余数 = " << result << endl;

x = -17.50, y = 2.0;
result = fmod(x, y);
cout << x << "/" << y << " 的余数 = " << result << endl;

return 0;
}

当你运行程序时,输出将会是:

7.5/2.1 的余数 = 1.2
-17.5/2 的余数 = -1.5

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

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
double x = 12.19, result;
int y = -3;

result = fmod(x, y);
cout << x << "/" << y << " 的余数 = " << result << endl;

y = 0;
result = fmod(x, y);
cout << x << "/" << y << " 的余数 = " << result << endl;

return 0;
}

当你运行程序时,输出将会是:

12.19/-3 的余数 = 0.19
12.19/0 的余数 = -nan