gpt4 book ai didi

ocaml - 如何在 OCaml 中使用正常的模运算

转载 作者:行者123 更新时间:2023-12-02 17:00:47 25 4
gpt4 key购买 nike

在 OCaml -1 mod 3;; 中返回 -1 但我希望结果为 2。是否有其他额外的模指令或类似指令?

最佳答案

Ocaml 遵循模的 C 定义:

When integers are divided, the result of the / operator is the algebraic quotient with any fractional part discarded.90) If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a.

90) This is often called ''truncation toward zero''.

这意味着它给出 -n+1 到 n-1 或 0 到 n-1 范围内的余数。这是部门实现方式的一个不幸的副作用。对绝对值进行除法,最后修正符号。

要获得正模,您可以使用:

# let (mod) x y = ((x mod y) + y) mod y;;
val ( mod ) : int -> int -> int = <fun>
# -1 mod 3;;
- : int = 2
# 4 mod 3;;
- : int = 1

# let (mod) x y = let res = x mod y in if res < 0 then res + y else res;;
val ( mod ) : int -> int -> int = <fun>

关于ocaml - 如何在 OCaml 中使用正常的模运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54293362/

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