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 就可以实现,不过我暂时不改了,也许后面有道题目会让做这个事情,到时候再说。

相关推荐
xinxiyinhe2 天前
github免费编程类工具汇总与评估(二)
前端·后端·编程
HyperAI超神经6 天前
【TVM教程】使用自定义调度规则(Sketch Rule)在 CPU 上自动调度稀疏矩阵乘法
人工智能·深度学习·矩阵·编程·cpu·计算机语言·tvm
skywalk81637 天前
DrRacket是一款专为Scheme和Racket编程语言设计的集成开发环境(IDE)
ide·lisp·drracket
大模型铲屎官9 天前
玩转C#函数:参数、返回值与游戏中的攻击逻辑封装
开发语言·游戏·c#·编程·参数·函数·返回值
网络研究院11 天前
Oracle 公布 Java 的五大新功能
java·oracle·编程·更新·功能
大模型铲屎官18 天前
Python 科学计算与机器学习入门:NumPy + Scikit-Learn 实战指南
开发语言·人工智能·python·机器学习·numpy·编程·scikit-learn
大模型铲屎官23 天前
Python 性能优化:从入门到精通的实用指南
开发语言·人工智能·pytorch·python·性能优化·llm·编程
漫谈网络1 个月前
序列化选型:字节流抑或字符串
python·编程
程序猿看视界1 个月前
「读书计划」《啊哈!算法》7日结构化学习规划
数据结构·编程·算法竞赛·学习计划·算法学习
charlie1145141911 个月前
从单片机的启动说起一个单片机到点灯发生了什么下——使用GPIO点一个灯
单片机·嵌入式硬件·学习·编程·教程·gpio