请编写一个 Python 程序,将用户输入的一个 1~999 的整数转换成其对应的英文表示,
例如,729将被转换成sevenhundredandtwentynine。要求,在程序中尽可能地使用函数封装一些常用的转换,不得少于3个函数。...
例如,729 将被
转换成 seven hundred and twenty nine。要求,在程序中尽可能地使用函数封装一些常用的转换,不得少
于 3 个函数。 展开
转换成 seven hundred and twenty nine。要求,在程序中尽可能地使用函数封装一些常用的转换,不得少
于 3 个函数。 展开
1个回答
展开全部
def unit_to_word(u):
convert_table = {
0: "zero",
1: "one",
2: "two",
3: "three",
4: "four",
5: "five",
6: "six",
7: "seven",
8: "eight",
9: "nine",
}
return convert_table[u]
def tens_to_word(t):
convert_table = {
0: "",
10: "ten",
11: "eleven",
12: "twelve",
13: "thirteen",
14: "fourteen",
15: "fifteen",
16: "sixteen",
17: "seventeen",
18: "eighteen",
19: "nineteen",
2: "twenty",
3: "thirty",
4: "forty",
5: "fifty",
6: "sixty",
7: "seventy",
8: "eighty",
9: "ninety",
}
if 9 < t < 20:
return convert_table[t]
else:
tens = convert_table[t/10] + " " + unit_to_word(t%10)
return tens
def hundreds_to_word(h):
if h > 99:
word = unit_to_word(h/100) + " hundred"
tens = h % 100
if tens == 0:
return word
else:
return word + " and " + tens_to_word(tens)
else:
return tens_to_word(h)
for test in [0, 5, 19, 23, 100, 700, 711, 729]:
print test, "=>", hundreds_to_word(test)
测试结果输出如下:
0 => zero
5 => five
19 => nineteen
23 => twenty three
100 => one hundred
700 => seven hundred
711 => seven hundred and eleven
729 => seven hundred and twenty nine
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询