c++ - Is div function useful (stdlib.h)? -



c++ - Is div function useful (stdlib.h)? -

there function called div in c,c++ (stdlib.h)

div_t div(int numer, int denom); typedef struct _div_t { int quot; int rem; } div_t;

but c,c++ have / , % operators.

my question is: "when there / , % operators, div function useful?"

the div() function returns construction contains quotient , remainder of partition of first parameter (the numerator) sec (the denominator). there 4 variants:

div_t div(int, int) ldiv_t ldiv(long, long) lldiv_t lldiv(long long, long long) imaxdiv_t imaxdiv(intmax_t, intmax_t (intmax_t represents biggest integer type available on system)

the div_t construction looks this:

typedef struct { int quot; /* quotient. */ int rem; /* remainder. */ } div_t;

the implementation utilize / , % operators, it's not complicated or necessary function, part of c standard (as defined [iso 9899:201x][1]).

see implementation in gnu libc:

/* homecoming `div_t' representation of numer on denom. */ div_t div (numer, denom) int numer, denom; { div_t result; result.quot = numer / denom; result.rem = numer % denom; /* ansi standard says |quot| <= |numer / denom|, numer / denom computed in infinite precision. in other words, should truncate quotient towards zero, never -infinity. machine partition , remainer may work either way when 1 or both of numer or denom negative. if 1 negative , quot has been truncated towards -infinity, rem have same sign denom , opposite sign of numer; if both negative , quot has been truncated towards -infinity, rem positive (will have opposite sign of numer). these considered `wrong'. if both num , denom positive, result positive. boils downwards to: if numer >= 0, rem < 0, got wrong answer. in case, right answer, add together 1 quot , subtract denom rem. */ if (numer >= 0 && result.rem < 0) { ++result.quot; result.rem -= denom; } homecoming result; }

c++ c integer-division

Comments

Popular posts from this blog

iphone - Dismissing a UIAlertView -

intellij idea - Update external libraries with intelij and java -

javascript - send data from a new window to previous window in php -