sicp每日一题[2.1]

Exercise 2.1

Exercise 2.1: Define a better version of make-rat that handles both positive and negative arguments. make-rat should normalize the sign so that if the rational number is positive, both the numerator and denominator are positive, and if the rational number is negative, only the numerator is negative.


第一章学完了,今天开始学习第二章,目前还没有遇到什么问题,这道题也比较简单,只要注意到"分子分母同时为正,或者分子为负,分母为正,不需要改变符号;分子分母同时为负,或者分子为正,分母为负,分子分母都需要改变符号"这一点,就可以很容易地实现题目要求。

复制代码
; (make-rat ⟨n⟩ ⟨d ⟩) returns the rational number whose numerator is the integer ⟨n⟩ and whose denominator is the integer ⟨d ⟩.
(define (make-rat n d)
  (let ((n (/ n (gcd n d)))
        (d (/ d (gcd n d))))
    ; 分子分母同时为正,或者分子为负,分母为正,不需要改变符号
    ; 分子分母同时为负,或者分子为正,分母为负,分子分母都需要改变符号
    (if (or (and (positive? n) (positive? d))
            (and (negative? n) (positive? d)))
        (cons n d)
        (cons (- 0 n) (- 0 d)))))

; (numer ⟨x⟩) returns the numerator of the rational number ⟨x⟩.
(define (numer x) (car x))

; (denom ⟨x⟩) returns the denominator of the rational number ⟨x⟩.
(define (denom x) (cdr x))

(define (add-rat x y)
  (make-rat (+ (* (numer x) (denom y))
               (* (numer y) (denom x)))
            (* (denom x) (denom y))))

(define (sub-rat x y)
  (make-rat (- (* (numer x) (denom y))
               (* (numer y) (denom x)))
            (* (denom x) (denom y))))

(define (mul-rat x y)
  (make-rat (* (numer x) (numer y))
            (* (denom x) (denom y))))

(define (div-rat x y)
  (make-rat (* (numer x) (denom y))
            (* (denom x) (numer y))))

(define (equal-rat? x y)
  (= (* (numer x) (denom y))
     (* (numer y) (denom x))))

(define (print-rat x)
  (newline)
  (display (numer x))
  (display "/")
  (display (denom x)))


(print-rat (make-rat -1 2))
(print-rat (make-rat 1 2))

(define neg-one-half (make-rat -1 2))
(define one-third (make-rat 1 3))

(print-rat (add-rat neg-one-half one-third))
(print-rat (add-rat neg-one-half neg-one-half))
(print-rat (sub-rat neg-one-half one-third))
(print-rat (mul-rat neg-one-half one-third))
(print-rat (div-rat neg-one-half one-third))

; 执行结果
-1/2
1/2
-1/6
-1/1
-5/6
-1/6
-3/2

可以看出这里还是有改进空间,-1/1 写成 -1 就行,利用 gcd 就可以实现,不过我暂时不改了,也许后面有道题目会让做这个事情,到时候再说。

相关推荐
爱喝白开水a2 天前
从零开始学无监督学习:图像混合与标签平滑技术详解,收藏不走丢
人工智能·深度学习·学习·ai·大模型·编程·ai大模型
网络安全大学堂4 天前
【网络安全入门基础教程】网络安全就业方向(非常详细)零基础入门到精通,收藏这篇就够了
网络·安全·web安全·计算机·网络安全·程序员·编程
smilejingwei6 天前
数据分析编程第六步:大数据运算
java·大数据·开发语言·数据分析·编程·esprocspl
skywalk81639 天前
升级DrRacket8.10到8.18版本@Ubuntu24.04
linux·运维·服务器·lisp·racket
程序员鱼皮23 天前
爆肝2月,我的 AI 代码生成平台上线了!
java·前端·编程·软件开发·项目
程序员鱼皮1 个月前
刚刚,GPT-5 炸裂登场!可免费使用
计算机·ai·互联网·编程
HW-BASE1 个月前
C语言的结构体与联合体
c语言·单片机·嵌入式·编程·c
网络安全大学堂1 个月前
【网络安全入门基础教程】TCP/IP协议深入解析(非常详细)零基础入门到精通,收藏这一篇就够了
网络协议·tcp/ip·web安全·计算机·黑客·程序员·编程
悦悦子a啊1 个月前
Python之--集合
开发语言·python·编程
程序员鱼皮2 个月前
会Vibe Coding的同事:我一个人干掉整个技术部!
ai·程序员·互联网·编程·开发·代码