div() — Calculate Quotient and Remainder
Format
#include <stdlib.h>
div_t div(int numerator, int denominator);
Language Level
ANSI
Threadsafe
Yes
However, only the function version is threadsafe. The macro version is NOT threadsafe.
Description
The div()
function
calculates the quotient and remainder of the division of numerator by denominator.
Return Value
The div()
function
returns a structure of type div_t, containing both the quotient int
quot and the remainder int rem. If the return value
cannot be represented, its value is undefined. If denominator is 0,
an exception will be raised.
Example
This example uses
div()
to calculate
the quotients and remainders for a set of two dividends and two divisors.
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
int num[2] = {45,-45};
int den[2] = {7,-7};
div_t ans; /* div_t is a struct type containing two ints:
'quot' stores quotient; 'rem' stores remainder */
short i,j;
printf("Results of division:\n");
for (i = 0; i < 2; i++)
for (j = 0; j < 2; j++)
{
ans = div(num[i],den[j]);
printf("Dividend: %6d Divisor: %6d", num[i], den[j]);
printf(" Quotient: %6d Remainder: %6d\n", ans.quot, ans.rem);
}
}
/***************** Output should be similar to: *****************
Results of division:
Dividend: 45 Divisor: 7 Quotient: 6 Remainder: 3
Dividend: 45 Divisor: -7 Quotient: -6 Remainder: 3
Dividend: -45 Divisor: 7 Quotient: -6 Remainder: -3
Dividend: -45 Divisor: -7 Quotient: 6 Remainder: -3
**********************************************************/