最近我发现需要使用 C++ 中的 fmod()
函数来计算两个 long double 操作数的模数。
但我也看到 C++ 中有一些 “remainder” 函数几乎可以完成相同的工作。
这两个函数有什么区别?
最佳答案
C++ 中的 remainder()
函数计算分子/分母的浮点余数(四舍五入到最接近的值)。
余数 (x, y)
= x - rquote * y
其中 rquote 是 x/y 的结果,四舍五入到最接近的整数值(中间情况四舍五入到偶数)。
另一方面,C++ 中的 fmod()
函数计算分子/分母的浮点余数(向零舍入)。
fmod (x, y)
= x - tquote * y
其中 tquote 被截断,即 x/y 的结果(向零舍入)。
例子
double x = 7.5, y = 2.1;
double result = remainder(x, y);// output is -0.9
double result2 = fmod(x, y);// output is 1.2
关于c++ - C++ 函数 'remainder' 和 'fmod' 之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25734144/