Share via


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 別 的結構,其中包含商數和餘數。 型別引數的 longldiv_t 傳回值為 ,且具有 型 long longlldiv_t 別引數的傳回值為 。 div_tldiv_tlldiv_t 類型定義于 < stdlib.h > 中。

備註

div 式會 numer 除以 denom ,並計算商數和餘數。 div_t 結構包含商數 quot 和餘數 rem。 商號的正負號與數學商的正負號相同。 其絕對值是小於數學商絕對值的最大整數。 如果分母為 0,程式會終止並出現錯誤訊息。

採用 型 long 別引數的 多載 div ,或 long long 只能供 C++ 程式碼使用。 傳回型 ldiv_t 別和 lldiv_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