打印答案,“应该”和所需答案在一行[方案(初级学生语言)]

问题描述 投票:1回答:1

我目前正在解决Ex。 3.3.1其中:

练习3.3.1。美国使用英国(长度)测量系统。世界其他地方使用公制系统。因此,出国旅行的人和与外国合作伙伴进行交易的公司通常需要将英制测量值转换为公制测量值,反之亦然。

这是一个表格,显示了英语系统的六个主要长度测量单位:12

英制公制1英寸= 2.54厘米1英尺= 12英寸1码= 3英尺1杆= 5(1/2)码。 1 furlong = 40 rd。 1英里= 8英尺。开发功能英寸 - >厘米,英尺 - >英寸,码 - >英尺,杆 - >码,弗隆 - >杆,英里 - >弗隆。

然后开发功能脚 - > cm,码 - > cm,棒 - >英寸,英里 - >英尺。

提示:尽可能重用功能。使用变量定义来指定常量。

;; Contract: inches->cm

;; Purpose: to convert inches to centimeters

;; Examples: (inches->cm 22/7) should be 7.9828514

;; Definition: [refines the header]
(define (inches->cm in)
  (* in 2.54))

;; Tests
(inches->cm 22/7) "should be" 7.98287514

当我运行程序时,它运行如下:

7.98285714
"should be"
7.98285714

我一直在考虑的一个可能的缺陷是,如果我的代码具有多个具有多个设计配方的函数,如果我的程序运行如下,那么我将更难阅读:

7.98285714
"should be"
7.98285714
-11.9928
"should be"
-11.9928
9.4247736
"should be"
9.4247736

我只花时间弄清楚哪个是哪个。有没有办法使程序像下面的代码一样运行?

7.98285714 "should be" 7.98285714

-11.9928 "should be" -11.9928

9.4247736 "should be" 9.4247736

我仍然是这个“功能编程”范例和编程语言的新手,我不知道是否有像C中的printf()和/或\n之类的东西。但请耐心等待我。

functional-programming scheme lisp racket
1个回答
2
投票

如果你的问题是结果是用不同的行打印的,试试这个 - 它适用于初学者语言:

(define (print actual expected)
  (string-append
   (number->string (exact->inexact actual))
   " should be "
   (number->string (exact->inexact expected))))

(print (inches->cm 22/7) 7.98287514)
=> "3.142857142857143 should be 7.98287514"

如果您不受限于初学者的语言,这将是Racket中更简单的替代方案:

(printf "~a should be ~a~n" (inches->cm 22/7) 7.98287514)

或者甚至更好,使用check-expect或其他一些单元测试框架,有更适合这项工作的工具。不要重新发明轮子!

© www.soinside.com 2019 - 2024. All rights reserved.