我尝试使用 C++ 的 %
运算符获得 -1 模 1000000007 的结果
和 fmod
功能。
输出为 -1
,但 -1 modulo 1000000007==1000000006
。
我做错了什么?
最佳答案
说白了,你拿错算子了。
C++ 和 C %
不是模,而是余数。
assert(a / b * b + a % b == a); // for integral types
如果a
是非负数,则模数和余数相同。
否则返回值为负,只需添加b
。
template<class T>
inline constexpr auto
modulo(T a, T b) -> decltype(a%b) {
auto r = a % b;
if (r < 0) r += b;
return r;
}
或者(也)对于 C:
#define modulo(a, b) (a % b < 0 ? a % b + b : a % b)
为了完整性:在 C++11 之前,a/b
可以总是向下舍入而不是总是为 0,尽管 C++03 已经有一个注释,下一个标准可能会强制舍入到0.
Modulo is the remainder of euclidiean division, and always in range 0 <= modulo < divisor
In mathematics, the remainder is the amount "left over" after performing some computation.
关于c++ - 如何在 C++ 中计算 -1 模 1000000007,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26079469/