Mike12670
Mike12670

Reputation: 23

Undesired output in Racket

I'm working on a homework assignment and am a little bit confused as to what produced this output. Here is the code:

#lang racket
(define (my_calc calcType radius); define the function and set up the parameters
  (define PI 3.1416); define PI
  (cond ((and (= calcType 1) (positive? radius))); check to see whether the calc function is one and the radius is positive
        ((* 2 PI radius radius)); return the area of a circle
        ((and (= calcType 2) (positive? radius))); check to see whether the calc function is 2 and the radius is positive
        ((* (/ 4 3) PI radius radius radius)); return the volume of a sphere
        (else #f); if calc function is not 1 or 2 or the radius is not positive, return false
  )
)
(my_calc 1 10)
(my_calc 2 10)
(my_calc 0 1)
(my_calc 1 0)

and here is the output:

#t
628.32
6.2832
0

I have no idea why the first one would return true, it should return the area of a circle. There isn't even a return statement that would allow that. The second one seems to work just fine. The third one should produce false, but it produces the second answer divided by a hundred for some reason. And the 0 at the bottom is beyond me. Can anyone help me? Thank you.

Upvotes: 1

Views: 58

Answers (1)

21rw
21rw

Reputation: 1126

Your first procedure in a cond case has to be the test expression followed by the result. See the documentation, https://docs.racket-lang.org/reference/if.html.

For example:

(cond
   [; test expression
    (and (= calcType 2) (positive? radius))
    ; following result
    ((* (/ 4 3) PI radius radius radius))]

   [else whatever]
)

I would recommend using square brackets for each cond case for legibility.

In your case,

[(and (= calcType 1) (positive? radius))]

The test expression is (and (= calcType 1) (positive? radius)) but there is no following procedure.

You have the same problem for all of your cond cases. Good luck.

Upvotes: 1

Related Questions