如何一步求出商和余数?

问题描述 投票:0回答:2

可能重复:
除法同时求余数?

是否可以一步获得整数除法的商和余数,即不需要执行两次整数除法?

c++ c modulo integer-division
2个回答
27
投票

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


7
投票

是的,有一个名为

div()
(和
ldiv
,甚至可能是
lldiv
)的标准函数可以执行此操作。

© www.soinside.com 2019 - 2024. All rights reserved.