Div: what changed
Revision 0 to 1. Removed lines have a minus sign; added lines have a plus sign.
Title: Div
| Old | New | Line | |
|---|---|---|---|
| 1 | + | `div` is division in which the fractional part (remainder) is discarded. The expression `a div b` returns the integer part of the result of dividing two integers. This is in contrast to the expression `a / b` which returns a [[Real|real]] result. | |
| 2 | + | ||
| 3 | + | Both sides of an expression using `div` must be one of the integer types. Using a `real` operand with `div` will result in a compile-time error: | |
| 4 | + | ||
| 5 | + | ` Error: Operator is not overloaded: […]` | |
| 6 | + | ||
| 7 | + | To get an integer result with a [`real`](https://www.freepascal.org/docs-html/rtl/system/real.html) operand, use [`trunc`](https://www.freepascal.org/docs-html/rtl/system/trunc.html) or [`round`](https://www.freepascal.org/docs-html/rtl/system/round.html) with the [[Slash|/ operator]]. | |
| 8 | + | ||
| 9 | + | To demonstrate what `div` does, consider the following example: | |
| 10 | + | ||
| 11 | + | ``` pascal | |
| 12 | + | program divDemo(input, output, stderr); | |
| 13 | + | ||
| 14 | + | var | |
| 15 | + | i: shortInt; | |
| 16 | + | j: shortInt; | |
| 17 | + | q: qWord; | |
| 18 | + | r: qWord; | |
| 19 | + | ||
| 20 | + | begin | |
| 21 | + | i := 16; | |
| 22 | + | j := 3; | |
| 23 | + | q := 1000; | |
| 24 | + | r := 300; | |
| 25 | + | ||
| 26 | + | writeLn(i div j); | |
| 27 | + | writeLn(i / j); | |
| 28 | + | writeLn(q div r); | |
| 29 | + | writeLn(q / r); | |
| 30 | + | end. | |
| 31 | + | ``` | |
| 32 | + | ||
| 33 | + | outputs: | |
| 34 | + | ||
| 35 | + | ``` bash | |
| 36 | + | $ ./divDemo | |
| 37 | + | 5 | |
| 38 | + | 5.3333333333333330E+000 | |
| 39 | + | 3 | |
| 40 | + | 3.3333333333333335E+000 | |
| 41 | + | ``` | |
| 42 | + | ||
| 43 | + | ## See also | |
| 44 | + | ||
| 45 | + | - [[Mod|mod]] – remainder of integer division | |
| 46 | + | - [[Trunc|trunc]] – retrieve integer part of real numbers | |
| 47 | + | - [[Round|round]] – round to integer | |
| 48 | + | - [`math.divmod`](https://www.freepascal.org/docs-html/rtl/math/divmod.html) – retrieve both quotient and remainder | |
| 49 | + | ||
| 50 | + | --- | |
| 51 | + | *From the Free Pascal wiki, page "Div", as it stood on 2021-08-31 after a change by Kai Burghardt, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).* |
