You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Elixir中是否存在divmod函数?单次返回除法商与余数

Does Elixir have a combined divmod function?

Great question! You’re absolutely right that Elixir’s standard library doesn’t ship with a built-in divmod function that returns both quotient and remainder in one go—right now, you’re limited to using the separate div/2 (for integer division) and rem/2 (for remainder) functions individually.

Why no built-in divmod?

Elixir’s design philosophy leans toward small, single-responsibility functions, and the core team has opted to keep division and remainder operations separate. Plus, since div/2 and rem/2 are both optimized and fast, there’s rarely a performance hit from calling them sequentially if you need both values.

Creating your own divmod function

If you want the convenience of a combined function, it’s trivial to implement one yourself that wraps the standard library functions:

defmodule MyMath do
  def divmod(a, b) do
    {div(a, b), rem(a, b)}
  end
end

This function will behave exactly like the separate div/2 and rem/2 calls, following Elixir’s rules (for example, the remainder will have the same sign as the dividend):

MyMath.divmod(10, 3)   # => {3, 1}
MyMath.divmod(-10, 3)  # => {-4, 2}
MyMath.divmod(10, -3)  # => {-4, -1}

You can drop this into a utility module in your project and use it whenever you need both values at once.

内容的提问来源于stack exchange,提问作者aef

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:41:04