如何在一步中得到商和余数

How can I get the quotient and the remainder in a single step?

本文关键字:余数 一步      更新时间:2023-10-16

可能重复:
同时进行除法运算和求余数运算?

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

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

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