In muldiv (A, B, C), A, B, and C are three integers, and an integer is returned at the same time.
The calculation method is similar to a * B/C or a * B Div C, but there are also differences.
// Example 1: var A, B, C, N1, N2: integer; begin A: = 4; B: = 3; C: = 2; N1: = A * B Div C; N2: = muldiv (A, B, C); showmessagefmt ('% d: % d', [N1, N2]); {6: 6} end;
// Example 2: after multiplying the first two 32-bit integers A and B in muldiv, a 64-bit integer is obtained first, so that the operation will not overflow as much as possible. vaR A, B, C, N1, N2: integer; begin A: = maxint Div 2; B: = 3; C: = 2; N1: = A * B Div C; {this operation will overflow} N2: = muldiv (A, B, C); {muldiv will calculate the correct result} showmessagefmt ('% d: % d', [N1, n2]); {-536870913: 1610612735} end;
// Example 3: muldiv is automatically rounded. vaR A, B, C, N1, N2: integer; begin A: = 1; B: = 7; C: = 4; N1: = A * B Div C; {This result only truncates the integer part} N2: = muldiv (A, B, C); {muldiv will be rounded to} showmessagefmt ('% d: % d', [N1, n2]); {1: 2} end;
// Example 4: If muldiv cannot be calculated, return-1var N1, N2: integer; begin N1: = muldiv (maxint, maxint, 2); N2: = muldiv (1, 2, 0); showmessagefmt ('% d: % d', [N1, N2]); {-1:-1} end;