C/div

Z Wikibooks, biblioteki wolnych podręczników.
< C

Deklaracja[edytuj]

div_t div (int numer, int denom);

Plik nagłówkowy[edytuj]

stdlib.h

Opis[edytuj]

Funkcja div zwraca w strukturze typu div_t wynik dzielenia zmiennej numer przez zmienną denom.[1]

Wartość zwracana[edytuj]

Struktura typu div_t. Typ div_t składa się z dwóch pól typu int:
  • quot będącego skrótem angielskiej nazwy quotient ( iloraz czyli wynik z dzielenia )
  • rem będącego skrótem angielskiej nazwy remainder ( reszta z dzielenia )
#include <cstdlib>

struct div_t
{
    int quot;
    int rem;
};

Przykład użycia[edytuj]

Ładowanie biblioteki :

#include <stdlib.h> // Data Type: div_t

definicja zmiennych  :

int n = 20; // ang. numerator = dzielna ( licznik ) 
int d = -6; // ang. denominator = dzielnik (mianownik )
div_t result; // ang. result = wynik

dzielenie całkowite :

result = div (n, d);

Rezultat zawiera dwa pola :

result.quot // iloraz = ang. quotient
result.rem // reszta = ang. remainder

Teraz  :

  • result.quot jest równy -3
  • result.rem jest równy 2


zwrócmy uwagę że :

  • iloraz, czyli result.quot odpowiada n/d
  • reszta, czyli result.rem odpowiada n % d
  • (n/d)*d + n%d powinno być równe n.


Testujemy:

/*
gcc d.c -lm -Wall -Wextra
./a.out

http://www.gnu.org/software/libc/manual/html_node/Integer-Division.html
*/
#include <stdio.h> // printf
#include <stdlib.h> // div_t

int main(){

 int n = 20;
 int d = 6;

 div_t result; // 
 result = div (n, d);
 // Now result.quot is 3 and result.rem is 2.
 printf(" %d = %d * %d + %d \n", n, result.quot, d, result.rem);

return 0;
}

Wynik :

  20 = 3 * 6 + 2 

Żródła[edytuj]

  1. stackoverflow question: what-is-the-purpose-of-the-div-library-function ?