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.
views:
248answers:
4
+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
2010-01-16 09:39:30
FLOOR does the division by itself.
Svante
2010-01-16 13:13:29
True, but it also works with a single argument.
Greg Hewgill
2010-01-16 20:59:06
+11
A:
(floor 7 2)
Ref: http://rosettacode.org/wiki/Basic_integer_arithmetic#Common_Lisp
KennyTM
2010-01-16 09:40:01
+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
2010-01-16 09:40:30
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
2010-01-16 16:55:22
+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
2010-01-16 11:54:42