views:

248

answers:

4

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

+1  A: 

Use the floor function. In SBCL:

* (floor (/ 7 2))

3
1/2

Two values are returned, the integer part and the fractional part.

Greg Hewgill
FLOOR does the division by itself.
Svante
True, but it also works with a single argument.
Greg Hewgill
+11  A: 
(floor 7 2)

Ref: http://rosettacode.org/wiki/Basic_integer_arithmetic#Common_Lisp

KennyTM
+1  A: 

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, that can be done with multiple-value-bind as follows:

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

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

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

I'm leaving the reference to multiple-value-bind in the answer, since it's an important function to be familiar with.

Eli Bendersky
how do i get the first value? does it return a list??
appusajeev
@appusajeev: I've updated the answer
Eli Bendersky
that's not needed. the first value is automatically passed to the next code. You need the MULTIPLE-VALUE-BIND if you want all values or some. (values (floor 7 2)) just returns the first.
Rainer Joswig
@Rainer: thanks, I've updated the answer
Eli Bendersky
+9  A: 

See FLOOR, CEILING and TRUNCATE in ANSI Common Lisp.

Examples (see the 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

Usually for division to integer TRUNCATE is used.

Rainer Joswig