(计划):将一个bigint分成几十,几百等。并进入包含英语

时间:2016-02-21 00:38:48

标签: scheme racket

所以我很难写这个程序 范围是一个需要大量的程序(比如1,000,000)并将其分成数字(即1,500,310 - > 1百万500,000 3百1 10 0一)。

#lang r5rs 
(define (three_names x)
  (let loop ((x x)
             (myList '()))
    (if (< x 10)
        (cons x myList)
        (loop (quotient x 10)
              (cons (remainder x 10) myList)))))

我已经得到它以便循环并将这些值返回到列表中,并提供stackoverflow的帮助。

(即,这将取100并将其放入'(1 0 0),这是有帮助的,但没有足够的帮助。我从星期三起就一直在敲我的头!)

1 个答案:

答案 0 :(得分:1)

我会选择这样的事情:

#lang r5rs 

(define (three-names n)
  (let loop ((n n)
             (units '((10 "one") (10 "ten") (10 "hundred") (1000 "thousand") (1000 "million")))
             (res ""))
    (if (or (zero? n) (null? units))
        res
        (let* ((unit (car units)) (div (car unit)) (txt (cadr unit)))
          (let ((q (quotient n div)) (r (remainder n div)))
            (loop q
                  (cdr units)
                  (string-append (number->string r) " " txt " " res)))))))

测试:

> (three-names 1500310)
"1 million 500 thousand 3 hundred 1 ten 0 one "
> (three-names 1001)
"1 thousand 0 hundred 0 ten 1 one "

修改

的替代版本
  • 适用于初始值0(之前的程序在这种情况下不会返回任何内容)
  • 使用符号并返回列表而不是字符串,如评论中所述
  • 在循环中有一个额外的显示,可以更清楚地显示&#34;单位&#34;被选中:

可能是:

(define (three-names n)
  (if (zero? n)
      "zero"
      (let loop ((n n)
                 (units '((10 one) (10 ten) (10 hundred) (1000 thousand) (1000 million)))
                 (res '()))
        (display n) (display " - ") (display res) (display " - ") (display units) (newline)
        (if (or (zero? n) (null? units))
            res
            (let* ((unit (car units)) (div (car unit)) (txt (cadr unit)))
              (let ((q (quotient n div)) (r (remainder n div)))
                (loop q
                      (cdr units)
                      (cons r (cons txt res)))))))))

现在:

> (display (three-names 1500310))
1500310 - () - ((10 one) (10 ten) (10 hundred) (1000 thousand) (1000 million))
150031 - (0 one) - ((10 ten) (10 hundred) (1000 thousand) (1000 million))
15003 - (1 ten 0 one) - ((10 hundred) (1000 thousand) (1000 million))
1500 - (3 hundred 1 ten 0 one) - ((1000 thousand) (1000 million))
1 - (500 thousand 3 hundred 1 ten 0 one) - ((1000 million))
0 - (1 million 500 thousand 3 hundred 1 ten 0 one) - ()
(1 million 500 thousand 3 hundred 1 ten 0 one)