C++ 中的 fmod() 函数计算 numerator/denominator 的浮点余数(向零舍入)。
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); // Additional overloads for other combinations of arithmetic types
fmod() 函数接受两个参数,并返回 double、float 或 long double 类型的值。此函数定义在 <cmath> 头文件中。
fmod() 参数
- x: 分子的值。
- y: 分母的值。
fmod() 返回值
fmod() 函数返回 x/y 的浮点余数。如果分母 y 为零,fmod() 返回 NaN(非数字)。
示例 1:fmod() 在 C++ 中如何工作?
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double x = 7.5, y = 2.1;
double result = fmod(x, y);
cout << "Remainder of " << x << "/" << y << " = " << result << endl;
x = -17.50, y = 2.0;
result = fmod(x, y);
cout << "Remainder of " << x << "/" << y << " = " << result << endl;
return 0;
}
运行程序后,输出将是
Remainder of 7.5/2.1 = 1.2 Remainder of -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 << "Remainder of " << x << "/" << y << " = " << result << endl;
y = 0;
result = fmod(x, y);
cout << "Remainder of " << x << "/" << y << " = " << result << endl;
return 0;
}
运行程序后,输出将是
Remainder of 12.19/-3 = 0.19 Remainder of 12.19/0 = -nan
另请阅读