### 输出fmod函数c ++

``````#include <iostream>
#include <cmath>
#include <limits>
using namespace std;

int main() {
double h = .1;
double x = 1;
int nSteps = abs(x / h);

double rem = fmod(x, h);
cout<<"fmod output is "<<rem<<endl;
if(abs(rem)<std::numeric_limits<double>::epsilon())
cout<<"fmod output is almost near 0"<<endl;

rem = remainder(x,h);
cout<<"remainder output is "<<rem<<endl;
if(abs(rem)<std::numeric_limits<double>::epsilon())
cout<<"remainder output is almost near 0"<<endl;

return 0;
}
``````

#### 1 个答案:

``````double fmod(double x, double y)
{
double result = std::remainder(std::fabs(x), (y = std::fabs(y)));
if (std::signbit(result)) result += y;
return std::copysign(result, x);
}
``````

`std::remainder`计算一个非常小的结果，几乎为零（-5.55112e-17使用1和0.1为我，-1.11022e-16为2和0.2）。但是，重要的是结果是否定，这意味着`std::signbit`返回true，导致`y`被添加到结果中，从而有效地使结果相等到`y`

`x`为2且`y`为0.2

``````double x = 2;
double y = .2;

int n = static_cast<int>(x/y);
double result = x - n*y;
std::cout << "Manual: " << result << std::endl;
std::cout << "fmod: " << std::fmod(x,y) << std::endl;
``````

fmod：0.2