?
This document uses PHP Chinese website manual Release
在頭文件<stdlib.h>中定義 | ||
---|---|---|
div_t div(int x,int y); | (1) | |
ldiv_t ldiv(long x,long y); | (2) | |
lldiv_t lldiv(long long x,long long y); | (3) | (自C99以來) |
在頭文件<inttypes.h>中定義 | ||
imaxdiv_t imaxdiv(intmax_t x,intmax_t y); | (4) | (自C99以來) |
用分母y計算分子x除法的商和余數(shù)。
同時計算商和余數(shù)。商是丟棄任何小數(shù)部分的代數(shù)商(截斷為零)。剩下的就是“* y + rem == x”。 | (直到C99) |
---|---|
同時計算商(表達式x / y的結(jié)果)和余數(shù)(表達式x%y的結(jié)果)。 | (自C99以來) |
x, y | - | integer values |
---|
如果余數(shù)和商可以表示為相應(yīng)類型的對象(分別為int,long,long long和imaxdiv_t),則將它們作為類型為div_t,ldiv_t,lldiv_t,imaxdiv_t的對象返回,定義如下:
struct div_t { int quot; int rem; };
或是
struct div_t { int rem; int quot; };
struct ldiv_t { long quot; long rem; };
或是
struct ldiv_t { long rem; long quot; };
struct lldiv_t { long long quot; long long rem; };
或是
struct lldiv_t { long long rem; long long quot; };
struct imaxdiv_t { intmax_t quot; intmax_t rem; };
或是
struct imaxdiv_t { intmax_t rem; intmax_t quot; };
如果余數(shù)或商不能表示,則為不確定的。
在C99之前,如果兩個操作數(shù)中的任何一個都是負數(shù),那么在內(nèi)置除法運算符和余數(shù)運算符中商的舍入方向和余數(shù)的符號是實現(xiàn)定義的,但在div和ldiv中定義明確。
在許多平臺上,單個CPU指令獲得商和余數(shù),并且該函數(shù)可以利用該指令,盡管編譯器通常能夠在合適的地方合并near /和%。
#include <stdio.h>#include <math.h>#include <stdlib.h> // demo only: does not check for buffer overflowvoid itoa(int n, int base, char* buf){ div_t dv = {.quot = n}; char* p = buf; do { dv = div(dv.quot, base); *p++ = "0123456789abcdef"[abs(dv.rem)]; } while(dv.quot); if(n<0) *p++ = '-'; *p-- = '\0'; while(buf < p) { char c = *p; *p-- = *buf; *buf++ = c; } // reverse} int main(void){ char buf[100]; itoa(12346, 10, buf); printf("%s\n", buf); itoa(-12346, 10, buf); printf("%s\n", buf); itoa(65535, 16, buf); printf("%s\n", buf);}
輸出:
12346-12346ffff
C11標(biāo)準(ISO / IEC 9899:2011):
7.8.2.2 imaxdiv函數(shù)(p:219)
7.22.6.2 div,ldiv和lldiv函數(shù)(p:356)
C99標(biāo)準(ISO / IEC 9899:1999):
7.8.2.2 imaxdiv函數(shù)(p:200)
7.20.6.2 div,ldiv和lldiv函數(shù)(p:320)
C89 / C90標(biāo)準(ISO / IEC 9899:1990):
4.10 div_t,ldiv_t
4.10.6.2 div函數(shù)
4.10.6.4 ldiv函數(shù)
fmodfmodffmodl(C99)(C99) | 計算浮點除法操作的剩余部分(函數(shù)) |
---|---|
remainderremainderfremainderl (C99)(C99)(C99) | 計算浮點除法運算的有符號余數(shù)(函數(shù)) |
remquoremquofremquol(C99)(C99)(C99) | 計算帶符號的余數(shù)以及除法操作(函數(shù))的最后三位 |
|div的 C ++文檔 |