【问题标题】:How can I get the quotient and the remainder in a single step? [duplicate]如何一步获得商和余数? [复制]
【发布时间】:2012-01-09 05:39:55
【问题描述】:

可能重复:
Divide and Get Remainder at the same time?

是否可以在一个步骤中同时获得整数除法的商和余数,即不执行两次整数除法?

【问题讨论】:

  • 你的意思是除法的“结果”?它被称为“商”。
  • 好吧,假设我调用“25 % 10”,结果为 5,因为 2x10 = 20 和 5 是余数,我想要得到的也是模运算中的 2,有可能吗?
  • 某些 CPU 和某些语言具有此功能,请参见例如stackoverflow.com/questions/3895081/…
  • 大多数编译器(应该)将int c = a % b; int d = a / b; 之类的东西优化为一个操作(例如,x86 上的div,它同时返回)。
  • 单步是什么意思?您是否正在寻找要调用的单个函数?您是否正在寻找能够生成单个汇编指令的东西?您是否正在寻找能够生成需要一定数量时钟周期才能执行的程序集的东西?

标签: c++ c modulo integer-division


【解决方案1】:

是的,有一个称为div()(和ldiv,甚至可能是lldiv)的标准函数可以做到这一点。

【讨论】:

    【解决方案2】:

    div 会这样做。请参阅reference 和示例:

    /* div example */
    #include <stdio.h>
    #include <stdlib.h>
    
    int main ()
    {
      div_t divresult;
      divresult = div (38,5);
      printf ("38 div 5 => %d, remainder %d.\n", divresult.quot, divresult.rem);
      return 0;
    }
    

    输出:

    38 div 5 => 7, remainder 3.
    

    编辑:

    C 规范说:

    7.20 通用实用程序

    The types declared are size_t and wchar_t (both described in 7.17),
    div_t
    which is a structure type that is the type of the value returned by the div function,
    ldiv_t
    which is a structure type that is the type of the value returned by the ldiv function, and
    lldiv_t
    which is a structure type that is the type of the value returned by the lldiv function.
    

    ...但没有说明div_t的定义是什么。

    【讨论】:

    • @ddriver:是的,但请看我的编辑。
    • 好的,非常感谢您的详细回复
    • 仅供参考 - GLIBC implementation of div 只是进行除法和模数运算,因此您什么也得不到。实际上,您获得的是函数调用开销。
    • @MikeSteinert:这取决于你的架构——例如 glibc 有一个 assembly implementation of div for Alpha
    猜你喜欢
    • 1970-01-01
    • 2018-12-07
    • 2011-08-01
    • 1970-01-01
    • 2021-08-18
    • 2020-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多