div, ldiv, lldiv

计算两个整数值的商和余数。

语法

div_t div(
   int numer,
   int denom
);
ldiv_t ldiv(
   long numer,
   long denom
);
lldiv_t lldiv(
   long long numer,
   long long denom
);
ldiv_t div(
   long numer,
   long denom
); /* C++ only */
lldiv_t div(
   long long numer,
   long long denom
); /* C++ only */

参数

numer
分子。

denom
分母。

返回值

使用 div 类型的参数调用的 int 将返回 div_t 类型的结构,其包含商和余数。 long 类型的带参数的返回值是 ldiv_tlong long 类型的带参数的返回值是 lldiv_tdiv_tldiv_tlldiv_t 类型在 <stdlib.h> 中定义的。

备注

div 函数将 numer 除以 denom,并计算商和余数。 div_t 结构包含商,quot 和余数,rem。 商的符号与数学商的符号相同。 其绝对值是小于数学商的绝对值的最大整数。 如果分母为 0,程序将终止并显示错误消息。

采用 longlong long 类型参数的 div 重载仅可供 C++ 代码使用。 返回类型 ldiv_tlldiv_t 包含成员 quotrem,它们与 div_t 的成员含义相同。

要求

例程 必需的标头
div, ldiv, lldiv <stdlib.h>

有关兼容性的详细信息,请参阅 兼容性

示例

// crt_div.c
// arguments: 876 13

// This example takes two integers as command-line
// arguments and displays the results of the integer
// division. This program accepts two arguments on the
// command line following the program name, then calls
// div to divide the first argument by the second.
// Finally, it prints the structure members quot and rem.
//

#include <stdlib.h>
#include <stdio.h>
#include <math.h>

int main( int argc, char *argv[] )
{
   int x,y;
   div_t div_result;

   x = atoi( argv[1] );
   y = atoi( argv[2] );

   printf( "x is %d, y is %d\n", x, y );
   div_result = div( x, y );
   printf( "The quotient is %d, and the remainder is %d\n",
           div_result.quot, div_result.rem );
}
x is 876, y is 13
The quotient is 67, and the remainder is 5

另请参阅

数学和浮点支持
imaxdiv