刚刚了解了递归,无法弄清楚如何使其发挥作用

时间:2016-09-30 08:29:41

标签: ruby recursion

我已经编写了一个程序来接收一个数字,然后用英文文本打印这个数字。这是我的第二次尝试,同时试图使其更加浓缩并重复更少。

只要数字<&lt;&lt; 100但是那个,我有问题。我尝试删除了gets,并在方法本身上有一个参数,但是它将错误从递归的行移到了行,将它的值添加到变量total。

我认为我现在的技能并不理解。递归对我来说仍然感觉像黑暗魔法。

def numberWords num
  #num = gets.chomp.to_i

  singles = ['one',     'two',       'three',    'four',     'five',
           'six',     'seven',     'eight',    'nine']
  tens = ['eleventy',     'twenty',    'thirty',   'forty',    'fifty',
           'sixty',   'seventy',   'eighty',   'ninety']
  teens = ['eleven',  'twelve',    'thirteen', 'fourteen', 'fifteen',
           'sixteen', 'seventeen', 'eighteen', 'nineteen']


  total = ""

  if num == 0
    puts "Zero"
  end

  current = num/1000
  if current > 0
    thousands = numberWords current
    total = total + thousands + "Thousands"
  end

  total = total + " "

  current = num / 100
  if current > 0
    hundreds = numberWords current
    total = total + hundreds + "Hundred"
  end

total = total + " "

  #TENS
  current = num/10
  if current > 1
    total = total + tens[current - 1]
  end

  total = total + " "
  #SINGLES

  num = num - (current*10)
  if num > 0
    total = total + singles[num - 1]
  end

    puts total

end

numberWords(2222)

1 个答案:

答案 0 :(得分:1)

试试这个版本:

def number_words(num)
  singles = ['one',     'two',       'three',    'four',     'five',
           'six',     'seven',     'eight',    'nine']
  tens = ['eleventy',     'twenty',    'thirty',   'forty',    'fifty',
           'sixty',   'seventy',   'eighty',   'ninety']
  teens = ['eleven',  'twelve',    'thirteen', 'fourteen', 'fifteen',
           'sixteen', 'seventeen', 'eighteen', 'nineteen']

  if num == 0
    return "zero"
  elsif
    num >= 1000
    q, r = num.divmod(1000)
    return number_words(q) + " thousand" + (r > 0 ? " " + number_words(r) : "") 
  elsif num >= 100
    q, r = num.divmod(100)
    return number_words(q) + " hundred" + (r > 0 ? " " + number_words(r) : "")
  elsif num >= 20
    q, r = num.divmod(10)
    return tens[q - 1] + (r > 0 ? "-" + number_words(r) : "")
  elsif num >= 11
    r = num % 10
    return teens[r - 1]
  elsif num == 10
    return "ten"
  end
  return singles[num - 1]
end

我将它从put输出更改为构建字符串。

重要的是订购,所以如果你想要处理数百万和数十亿,请按正确的顺序放置这些条款。

q和r是商和余数的缩写。

算术if(条件?true-statement:false-statement)用于压缩“零”字符串,它们不应该在那里。

基本思想是处理if子句中可以处理的内容,并将其他工作递归地传递给一个self。

以下是一些输出:

0: zero
1: one
2: two
3: three
10: ten
11: eleven
12: twelve
13: thirteen
20: twenty
21: twenty-one
22: twenty-two
23: twenty-three
30: thirty
39: thirty-nine
99: ninety-nine
100: one hundred
101: one hundred one
123: one hundred twenty-three
221: two hundred twenty-one
990: nine hundred ninety
999: nine hundred ninety-nine
1000: one thousand
2222: two thousand two hundred twenty-two