如何在一步中获得商和余数?

dte*_*ech 19 c c++ modulo integer-division

可能重复:同时
划分和获取剩余?

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

Joh*_*ing 24

div会这样做.参见参考和示例:

/* 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;
}
Run Code Online (Sandbox Code Playgroud)

输出:

38 div 5 => 7, remainder 3.
Run Code Online (Sandbox Code Playgroud)

编辑:

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.
Run Code Online (Sandbox Code Playgroud)

......但它没有说出定义div_t是什么.

  • 仅供参考 - [div`的GLIBC实现](http://bit.ly/uqny7z)只是划分和模数,所以你没有获得任何东西.实际上,你获得的是函数调用开销. (2认同)
  • @MikeSteinert:这取决于您的体系结构-例如glibc具有[div的Alpha程序集实现](http://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/alpha /div.S;h=d1a724d3758997ed800f995fba5ddf2ae82e148e;hb=febcd83655138bcb01b2680e170e6773a1ec813c) (2认同)

Gre*_*ill 8

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