gpt4 book ai didi

Python 和 C++ 模数

转载 作者:太空宇宙 更新时间:2023-11-04 02:48:58 24 4
gpt4 key购买 nike

我正在学习 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 % j have the same sign as j. 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 // j need to make i % j have the same sign as i.

There are few real use cases for i % j when j is negative. When j is positive, there are many, and in virtually all of them it’s more useful for i % j to be >= 0. If the clock says 10 now, what did it say 200 hours ago? -190 % 12 == 2 is useful; -190 % 12 == -10 is a bug waiting to bite.

关于Python 和 C++ 模数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44411646/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com