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

时间:2011-11-29 21:54:25

标签: c++ c modulo integer-division

  

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

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

2 个答案:

答案 0 :(得分:24)

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

答案 1 :(得分:8)

是的,有一个名为div()的标准函数(和ldiv,甚至可能是lldiv)。