?
本文檔使用 PHP中文網(wǎng)手冊(cè) 發(fā)布
在頭文件<math.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) | (since C99) |
Defined in header <inttypes.h> | ||
imaxdiv_t imaxdiv( intmax_t x, intmax_t y ); | (4) | (since C99) |
用分母x
來(lái)計(jì)算分子除法的商和余數(shù)y
。
同時(shí)計(jì)算商和余數(shù)。商是丟棄任何小數(shù)部分的代數(shù)商(截?cái)酁榱悖?。剩下的就是? y + rem == x”。 | (直到C99) |
---|---|
同時(shí)計(jì)算商(表達(dá)式x / y的結(jié)果)和余數(shù)(表達(dá)式x%y的結(jié)果)。 | (自C99以來(lái)) |
x,y | - | 整數(shù)值 |
---|
如果這兩個(gè)余數(shù)和商可以表示為相應(yīng)的類型的對(duì)象(INT,很久長(zhǎng),imaxdiv_t,分別地),同時(shí)返回作為類型的對(duì)象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之前,如果兩個(gè)操作數(shù)中的任何一個(gè)都是負(fù)數(shù),那么在內(nèi)建的除法運(yùn)算符和余數(shù)運(yùn)算符中,商的舍入方向和余數(shù)的符號(hào)是實(shí)現(xiàn)定義的,但是在div
和中定義明確ldiv
。
在許多平臺(tái)上,單個(gè)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)準(zhǔn)(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)準(zhǔn)(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)準(zhǔn)(ISO / IEC 9899:1990):
4.10 div_t,ldiv_t
4.10.6.2 div函數(shù)
4.10.6.4 ldiv函數(shù)