一、题目
二、示例
三、代码
list1 = ['零','壹','贰','叁','肆','伍','陆','柒','捌','玖','拾',
'拾壹','拾贰','拾叁','拾肆','拾伍','拾陆','拾柒','拾捌','拾玖']
def fun100(num): # 100以内的数字转换
temp = []
if num < 20:
if num < 10:
temp.append('零')
temp.append(list1[num])
else:
temp.append(list1[num // 10])
temp.append('拾')
if num % 10 != 0:
temp.append(list1[num % 10])
return temp
def fun1000(num): # 1000以内的数字转换
temp = []
if num < 100:
temp.append('零')
temp += fun100(num)
else:
temp.append(list1[num // 100])
temp.append('佰')
if num % 100 != 0:
if num % 100 < 10:
temp.append('零')
temp += fun100(num % 100)
return temp
def fun10000(num): # 10000以内的数字转换
temp = []
if num < 1000:
temp.append('零')
temp += fun1000(num)
else:
temp.append(list1[num // 1000])
temp.append('仟')
if num % 1000 != 0:
if num % 1000 < 100:
temp.append('零')
temp += fun1000(num % 1000)
return temp
def decimals(num): # 小数部分数字转换
temp = []
if num[0] != '0':
temp.append(list1[int(num[0])])
temp.append('角')
if num[1] != '0':
temp.append(list1[int(num[1])])
temp.append('分')
return temp
while True:
try:
yuan, jiaofen = input().split('.')
yuan = int(yuan)
result = []
a = yuan // 100000000
b = (yuan // 10000) % 10000
c = yuan % 10000
if a > 0:
result += fun10000(a)
result.append('亿')
if b > 0:
result += fun10000(b)
result.append('万')
if c > 0:
result += fun10000(c)
if len(result) > 0:
result.append('元')
if int(jiaofen) == 0:
result.append('整')
else:
result += decimals(jiaofen)
res = ''.join(result)
res = res.replace('零零','零') # replace() 用另一个指定的短语替换一个指定的短语。
res = res.strip('零') # strip()方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。
print('人民币' + res)
except:
break
四、算法说明
分别建立100,1000,10000以内的数字转换子函数;
然后将整数部分调用各个子函数,进行转化;
数字位数差两位就加‘零’
,用‘零’
替换‘零零’
,再把头部的‘零’
去掉。
注意:
replace() 方法用另一个指定的短语替换一个指定的短语;
strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。
胡萝卜
2022年2月28日21:33:19
我不知道将去向何方,但我已在路上! |
---|
时光匆匆,虽未曾谋面,却相遇于斯,实在是莫大的缘分,感谢您的到访 ! |