計算兩個整數值的商數和餘數。
語法
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_t、 ldiv_t和 lldiv_t 類型定義於 <stdlib.h> 中。
備註
函 div 式會 numer 除以 denom ,並計算商數和餘數。 div_t 結構包含商數 quot 和餘數 rem。 商號的正負號與數學商的正負號相同。 其絕對值是小於數學商絕對值的最大整數。 如果分母為 0,程式會終止並出現錯誤訊息。
接受 型long別自變數的 多載div,或long long只能用於C++程序代碼。 傳回型 ldiv_t 別和 lldiv_t 包含成員 quot 和 rem,其意義與的成員 div_t相同。
需求
| 常式 | 必要的標頭 |
|---|---|
div、 、 ldivlldiv |
<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