20

可能重复:
同时除法和获取余数?

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

4

2 回答 2

26

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;
}

输出:

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是什么。

于 2011-11-29T22:00:14.963 回答
8

Yes, there is a standard function called div() (and ldiv, and maybe even lldiv) that does this.

于 2011-11-29T21:59:05.737 回答