Integer division in Common Lisp?

When I do (/ 7 2) , what should I do to get result 3 ? If I do this (/ 7 2.0), I get 3.5 , which is as expected.

+7
casting lisp clisp
source share
5 answers
+16
source share

See FLOOR, CEILING, and TRUNCATE in ANSI Common Lisp.

Examples (see positive and negative numbers):

 CL-USER 218 > (floor -5 2) -3 1 CL-USER 219 > (ceiling -5 2) -2 -1 CL-USER 220 > (truncate -5 2) -2 -1 CL-USER 221 > (floor 5 2) 2 1 CL-USER 222 > (ceiling 5 2) 3 -1 CL-USER 223 > (truncate 5 2) 2 1 

Commonly used division by integer is TRUNCATE.

+17
source share

You can use the floor function:

 (floor 7 2) 3 1 

Note that it returns multiple values, and you only need the first one. Since floor returns multiple values, this can be done using multiple-value-bind as follows:

 (multiple-value-bind (qr) (floor 7 2) q) => 3 

Edit: As Rainer notes in his comment, you can simply pass the floor result as an argument if all you need is private.

 [1]> (floor 7 2) 3 ; 1 [2]> (+ (floor 7 2) 5) 8 [3]> 

I leave a link to multiple-value-bind in the answer, as this is an important function that you are familiar with.

+3
source share

Use the floor function. In SBCL:

 * (floor (/ 7 2)) 3 1/2 

Two values ​​are returned: the integer part and the fractional part.

+1
source share

My solution is to define a div function:

 (defun div (nd) (multiple-value-bind (qr) (floor nd) q)) > (div 7 2) 3 
0
source share

All Articles