C Library Functions -ldiv()

C Standard Library - <stdlib.h>

Description

C Library Functionsdiv_t ldiv(long int numer, long int denom)holdnumer (numerator)divided bydenom (denominator), that is, used to calculate the quotient and remainder of two long integer values.

Declaration

Below is the declaration of the ldiv() function.

ldiv_t ldiv(long int numer, long int denom)

Parameter

  • numer -- numerator.
  • denom -- denominator.

Return Value

This function returns a value of the structure defined in <cstdlib>, which has two members, such asldiv_t:long quot; long rem;, which respectively represent the quotient and remainder of the division.

The purpose of the ldiv() function is to avoid redundant calculations when the quotient and remainder need to be computed at the same time, because the remainder can also be obtained while calculating the quotient. Moreover, when the dividend or divisor is negative, the result of ldiv() will conform to the rule of rounding toward zero.

Example

The following example demonstrates the usage of the ldiv() function.

Example

#include <stdlib.h>
#include <stdio.h>

int main() {
    // The dividend is 11, the divisor is 3
    long int numer = 11;
    long int denom = 3;

    ldiv_t result = ldiv(numer, denom);

    printf("Quotient = %ld\n", result.quot);
    printf("Remainder = %ld\n", result.rem);

    return 0;
}

Let us compile and run the above program, which will produce the following result:

商 = 3
余数 = 2

C Standard Library - <stdlib.h>

other extensions