《计算机程序的构造与解释》习题自编代码(第1章)(未完待更)

注:
1. DrRacket下编写;
2. 未使用块结构,主要是为了看起来更简洁;
3. 如有更优写法,欢迎批评指正;

1.3 返回三个数中较大的两个数的和

(define (sum-bigest-two x y z)
  (cond ((and (< x y) (< x z)) (+ y z))
        ((and (< y x) (< y z)) (+ x z))
        ((and (< z x) (< z y)) (+ x y))))

1.7 以两次迭代guess的改变情况作为监测值实现开平方运算。(选定精确度为0.000001)

(define (sqrt-iter-s guess last x)
  (if (good-enough? guess last)
      guess
      (sqrt-iter-s (improve guess x) guess x)))
(define (good-enough? now last)
  (< (abs (- last now)) 0.000001))
(define (abs x)
  (cond((< x 0) (- x))
       ((= x 0) 0)
       ((> x 0) x)))
(define (improve guess x)
  (average guess (/ x guess)))
(define (average x y)
  (/ (+ x y) 2))
(define (sqrt-s x)
  (sqrt-iter-s 1.0 0 x))

1.8 实现立方根运算(由上述1.7的代码修改计算公式而来)

(define (cbrt-iter guess last x)
  (if (good-enough? guess last)
      guess
      (cbrt-iter (improve guess x) guess x)))
(define (good-enough? now last)
  (< (abs (- last now)) 0.000001))
(define (abs x)
  (cond((< x 0) (- x))
       ((= x 0) 0)
       ((> x 0) x)))
(define (improve guess x)
  (third (/ x (square guess)) (* 2 guess)))
(define (third x y)
  (/ (+ x y) 3))
(define (square x) (* x x))
(define (cbrt x)
  (cbrt-iter 1.0 0 x))

1.11

(1) 递归计算过程

(define (f-recu n)
  (if (< n 3)
      n
      (deal (f-recu (- n 1)) (f-recu(- n 2)) (f-recu(- n 3)))))
(define (deal x y z)
  (+ (* 1 x)
     (* 2 y)
     (* 3 z)))

(2) 迭代计算过程

(define (f n)
  (f-iter 0 1 2 n))
(define (f-iter a b c count)
  (if (< count 3)
      c
      (f-iter b c (improve a b c) (- count 1))))
(define (improve x y z)
  (+ (* 3 x)
     (* 2 y)
     (* 1 z)))

注意递归和迭代变量乘的顺序是恰好相反的,即123和321;

1.12
row表示行数,number表示该行的第几个数;
例如,(pascal 5 3)表示求第五行第三个数,结果为6;

(define (pascal row number)
  (if (or (= number 1) 
          (= row number) 
          (= row 2))
      1
      (+ (pascal (- row 1) (- number 1)) 
         (pascal (- row 1) number))))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值