python-牛客网之人民币转换

人民币转换

题目描述
考试题目和要点:

1、中文大写金额数字前应标明“人民币”字样。中文大写金额数字应用壹、贰、叁、肆、伍、陆、柒、捌、玖、拾、佰、仟、万、亿、元、角、分、零、整等字样填写。

2、中文大写金额数字到“元”为止的,在“元”之后,应写“整字,如532.00应写成“人民币伍佰叁拾贰元整”。在”角“和”分“后面不写”整字。

3、阿拉伯数字中间有“0”时,中文大写要写“零”字,阿拉伯数字中间连续有几个“0”时,中文大写金额中间只写一个“零”字,如6007.14,应写成“人民币陆仟零柒元壹角肆分“。
4、10应写作“拾”,100应写作“壹佰”。例如,1010.00应写作“人民币壹仟零拾元整”,110.00应写作“人民币壹佰拾元整”
5、十万以上的数字接千不用加“零”,例如,30105000.00应写作“人民币叁仟零拾万伍仟元整”

本题含有多组样例输入。

while True: #因为有多组输入
    try:
        money = input().strip()
        FindDot = money.index('.')
        CnUnit = ['壹','贰','叁','肆','伍','陆','柒','捌','玖', '拾']
        integralUnit = ['元', '拾', '佰', '仟', '万', '拾', '佰', '仟', '亿', '拾', '佰', '仟']
        integerPart = money[:-3] #输入的整数部分
        zero = 0
        a_output = "人民币"  #输出的开头
        if integerPart != '0':
            for i in range(len(integerPart)):
                if zero > 0 and int(integerPart[i]) != 0:#当前面有一个或多个数字为0,且当前数字不
                #为0时,输出“零”,并且重置zero
                    a_output += '零'
                    zero = 0
                if int(integerPart[i]) >= 1: #当数字不为0时,输出对应的汉字数字及单位
                    res = CnUnit[int(integerPart[i])-1]+integralUnit[len(integerPart)-i-1]
                    res = res.replace('壹拾', '拾') #如果是“壹拾”,则按照要求替换为“拾”
                    a_output += res
                else: #如果当前数字是0的话,zero加1
                    zero += 1
                #print(len(integerPart)-i-1 % 4,end='')
                length = len(integerPart)-i-1
                #print(length % 4, end='')
                #下面的第一个条件是为了区分上面的if条件,非零时已做处理,下面是处理当前数字为0的情况
                #比如输入数字105000.00,下面这个判断语句就是输出“万”字
                if int(integerPart[i]) == 0 and length != 0 and length % 4 == 0:
                    a_output += integralUnit[len(integerPart)-i-1]
            if money[-4] == '0':
                a_output += '元'
        #下面是分情况讨论小数部分
        if money[-2:] == '00':
            a_output += '整'
        elif money[-2] == '0':
            a_output += CnUnit[int(money[-1])-1] + '分'
        elif money[-1] == '0':
            a_output += CnUnit[int(money[-2])-1] + '角'
        else:
            a_output += CnUnit[int(money[-2])-1] + '角'+ CnUnit[int(money[-1])-1] + '分'
        for s in range(9):  #这个for循环是为了满足上面的第5点要求,使用replace去掉“零”
            if "万零" + CnUnit[s] + "仟" in a_output:
                a_output = a_output.replace("万零" + CnUnit[s] + "仟", "万" + CnUnit[s] + "仟")
        print(a_output)
    except:
        break

上面的代码是自己根据题目要求写的,花了比较久的时间,但是最终还是通过了,做这种题目,自己要多思考,不要急着去看看别人的代码,自己真正通过思考想出来的,最终才是自己的,才会有更多收获,愿和大家一起学习,共同进步!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

笑着的程序员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值