示例工程 02-syntax-c-go-java
02-syntax-c-go-java/03-negative-modulo/negative_modulo.py
"""演示 Python 的整除与取模:结果符号跟除数走,与 C 的截断相反。"""
from __future__ import annotations
def floor_div(a: int, b: int) -> int:
"""向下取整的整除。"""
return a // b
def modulo(a: int, b: int) -> int:
"""与 // 配套的取模,满足 a == (a // b) * b + a % b。"""
return a % b
def c_trunc_div(a: int, b: int) -> int:
"""模拟 C 的截断除法(向零取整)。"""
quotient = abs(a) // abs(b)
return quotient if (a >= 0) == (b >= 0) else -quotient
def table() -> list[tuple[int, int, int, int, int]]:
"""返回 (a, b, python_div, python_mod, c_div) 样例。"""
pairs = [(-7, 2), (7, -2), (-7, -2), (7, 2)]
return [(a, b, floor_div(a, b), modulo(a, b), c_trunc_div(a, b)) for a, b in pairs]
def main() -> None:
for a, b, div, mod, c_div in table():
print(f"{a:>3} // {b:>2} = {div:>3} | % = {mod:>2} | C trunc = {c_div:>3}")
if __name__ == "__main__":
main()