Div: what changed
Revision 1 to 2. Removed lines have a minus sign; added lines have a plus sign.
| Old | New | Line | |
|---|---|---|---|
| 1 | 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 | 2 | ||
| 3 | 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 | 4 | ||
| 5 | - | ||
| 5 | + | ```text | |
| 6 | + | Error: Operator is not overloaded: […] | |
| 7 | + | ``` | |
| 6 | 8 | ||
| 7 | 9 | 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 | 10 | ||
| 9 | 11 | To demonstrate what `div` does, consider the following example: | |
| 10 | 12 | ||
| 11 | 13 | ``` pascal | |
| 12 | 14 | program divDemo(input, output, stderr); | |
| 13 | 15 | ||
| 14 | 16 | var | |
| 15 | 17 | i: shortInt; | |
| 16 | 18 | j: shortInt; | |
| 17 | 19 | q: qWord; | |
| 18 | 20 | r: qWord; | |
| 19 | 21 | ||
| 20 | 22 | begin | |
| 21 | 23 | i := 16; | |
| 22 | 24 | j := 3; | |
| 23 | 25 | q := 1000; | |
| 24 | 26 | r := 300; | |
| 25 | 27 | ||
| 26 | 28 | writeLn(i div j); | |
| 27 | 29 | writeLn(i / j); | |
| 28 | 30 | writeLn(q div r); | |
| 29 | 31 | writeLn(q / r); | |
| 30 | 32 | end. | |
| 31 | 33 | ``` | |
| 32 | 34 | ||
| 33 | 35 | outputs: | |
| 34 | 36 | ||
| 35 | 37 | ``` bash | |
| 36 | 38 | $ ./divDemo | |
| 37 | 39 | 5 | |
| 38 | 40 | 5.3333333333333330E+000 | |
| 39 | 41 | 3 | |
| 40 | 42 | 3.3333333333333335E+000 | |
| 41 | 43 | ``` | |
| 42 | 44 | ||
| 43 | 45 | ## See also | |
| 44 | 46 | ||
| 45 | 47 | - [[Mod|mod]] – remainder of integer division | |
| 46 | 48 | - [[Trunc|trunc]] – retrieve integer part of real numbers | |
| 47 | 49 | - [[Round|round]] – round to integer | |
| 48 | 50 | - [`math.divmod`](https://www.freepascal.org/docs-html/rtl/math/divmod.html) – retrieve both quotient and remainder | |
| 49 | 51 | ||
| 50 | 52 | --- | |
| 51 | 53 | *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).* |
