返回顶部

收藏

数字转换成罗马数字

更多

[Ruby]代码

# Hash holding the roman values
# Values above 3999 are not accepted, as numerals with bars are required.
roman_map = Hash[ 1000 => "M", 900 => "CM", 500 => "D", 400 => "CD", 100 => "C", 90 => "XC", 50 => "L", 40 => "XL", 10 => "X", 9 => "IX", 5 => "V", 4 => "IV", 1 => "I"]

print "Enter number> "
arabic = gets.chomp.to_i
if arabic < 4000
  # Sort the keys, highest value (1000) first, then descending,
  # and parse values
  roman_map.keys.sort{ |a,b| b <=> a }.each do
    |n|
    # get roman numeral until the arabic number is too small,
    # in which case we'll try the smaller roman values
    while arabic >= n
      arabic = arabic-n
      print roman_map[n]
    end
  end
else 
  puts "Please enter number lower than 3999."
end

标签:ruby/rails

收藏

0人收藏

支持

0

反对

0