我正在研究Scheme程序,在某些地方我需要一对浮点计数器和与格式化字符串相同的计数器。我在将数字转换为字符串时遇到问题。
有人可以在代码中向我解释这些错误吗?
(letrec ((ground-loop (lambda (times count step)
(if (= times 250)
(begin
(display "exit")
(newline)
)
(begin
(display (* times step)) (newline)
(display (number->string (* times step)))(newline)
(newline)
(newline)
(ground-loop (+ times 1) (* times step) step)
)
)
)
))
(ground-loop 0 0 0.05)
)
输出的一部分看起来像这样
7.257.25
7.37.300000000000001
7.357.350000000000001
7.47.4
7.457.45
7.57.5
7.557.550000000000001
7.67.600000000000001
7.657.65
我知道浮点数不正确,并尝试了几种增加计数器的形式,但问题出在转换本身。
任何简单解决方案的想法?尝试使用显式四舍五入的数字,但这没有完成任务。结果甚至因IDE和环境而异。转换后我真的必须进行字符串操作吗?在我的情况下,很奇怪的是得到了精确的数字结果,但是字符串不可用。
谢谢
我认为您正在寻找格式化的输出。在球拍中,尝试替换此行:
(display (number->string (* times step)))
使用此:
(display (~r (* times step) #:precision 2))