我正在学习 C++,在尝试编写一个小程序时,我发现了一些奇怪的东西。这是关于模数: C++代码
cout << -325 - (-325 % 100) << endl;
// -300
cout << 325 - (325 % 100);
// 300
和python代码
print(-325 - (-325 % 100))
# -400
print(325 - (325 % 100))
# 300
有人可以向我解释一下吗?谢谢
请您参考如下方法:
这有点超出我的专业知识,但它可能是 python 遵循 Donald Knuth余数计算为:a + b*[a/b] 为 [] floor手术。这样:
a = -325
b = 100
print(a - b*math.floor(a/b))
print(math.floor(-3.25))
print(-325 -(a - b*math.floor(a/b)))
结果:
75
-4
-400
我有点惊讶 C++ 没有返回相同的结果(但我对这个主题的了解也不够)。
编辑:快速搜索了这个主题和learncpp提到了为什么 C++,特别是 C++ 11,总是将 floor 操作标准化为 0 的原因。我引用:
Prior to C++11, if either of the operands of integer division are negative, the compiler is free to round up or down! For example, -5 / 2 can evaluate to either -3 or -2, depending on which way the compiler rounds. However, most modern compilers truncate towards 0 (so -5 / 2 would equal -2). The C++11 specification changed this to explicitly define that integer division should always truncate towards 0 (or put more simply, the fractional component is dropped).
Also prior to C++11, if either operand of the modulus operator is negative, the results of the modulus can be either negative or positive! For example, -5 % 2 can evaluate to either 1 or -1. The C++11 specification tightens this up so that a % b always resolves to the sign of a.
关于 Python,您可以查看 divmod 的文档其中指出:
Take two (non complex) numbers as arguments and return a pair of numbers consisting of their quotient and remainder when using integer division. With mixed operand types, the rules for binary arithmetic operators apply. For integers, the result is the same as (a // b, a % b). For floating point numbers the result is (q, a % b), where q is usually math.floor(a / b) but may be 1 less than that. In any case q * b + a % b is very close to a, if a % b is non-zero it has the same sign as b, and 0 <= abs(a % b) < abs(b)
EDIT2:关于 Python Programming FAQ 的更多信息关于这个主题。
Why does -22 // 10 return -3?
It’s primarily driven by the desire that
i % jhave the same sign asj. If you want that, and also want:
i == (i // j) * j + (i % j)then integer division has to return the floor. C also requires that identity to hold, and then compilers that truncate
i // jneed to makei % jhave the same sign asi.There are few real use cases for
i % jwhenjis negative. Whenjis positive, there are many, and in virtually all of them it’s more useful fori % jto be>= 0. If the clock says 10 now, what did it say 200 hours ago?-190 % 12 == 2is useful;-190 % 12 == -10is a bug waiting to bite.
