首页 > 试题广场 >

人民币转换

[编程题]人民币转换
  • 热度指数:78226 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解

考试题目和要点:

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

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

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



输入描述:

输入一个double数



输出描述:

输出人民币格式

示例1

输入

151121.15

输出

人民币拾伍万壹仟壹佰贰拾壹元壹角伍分
示例2

输入

1010.00

输出

人民币壹仟零拾元整
"""
思路:
要求:
    1:需要判断金额是否为整数
    2:需要判断金额是否超过十万
    3:需要判断数字中间是否有零
总结:
    0.定义一个判断金额是否为整数的函数
        (1)整数:直接调用第二个函数
        (2)整数+小数:
                 整数部分调用第二个函数
                 处理小数部分
    1.定义一个切分整数部分金额的函数
        (1)判断整数部分是否超过十万
        (2)小于等于十万的部分怎么处理(数千加零)
             等于10万:后面一部分调用第二个函数
             小于10万:后面一部分调用第二个函数
        (3)大于10万的部分怎么处理(数千不加零)
             整数部分按4位切分,不足四位的前面补0
    2.定一个将四位数的金额转换成汉字表示的函数
        (1)千位&百位&十位为0,个位不为0
        (2)千位和百位都为0,十位&个位不为0
        (3)千位和百位都为0,十位不为0,个位为0
        (4)千位为0,百位不为0,十位&个位均为0
        (5)千位为0,百位不为0,十位为0,个位不为0
        (6)千位为0,百位不为0,十位不为0,个位为0
        (7)千位为0,百位&十位&个位不为0
        (8)千位不为零,百位为零,个位十位不为零
        (9)千位不为零,百位&十位为零,个位不为零
        (10)千位不为零,百位&十位&个位均为零
        (11)千位&百位不为0,十位为0,个位不为0
        (12)千位&百位&十位均不为0,个位为0
        (13)千位&百位&十位&个位均不为0
"""
# 元、角、分、零、整
dictChinese = {
    '0':'零','1':'壹','2':'贰','3':'叁','4':'肆','5':'伍','6':'陆','7':'柒',
    '8':'捌','9':'玖','10':'拾'
}

def intOrDouble(string):
    stringInt = ''
    stringDou = ''
    if '.' in string:
        stringInt,stringDou = string.split('.')
    else:
        stringInt = string
    # 表示小数部分
    resDou = ''
    if int(stringDou)<10:
        resDou = dictChinese[stringDou[1]] + '分'
    elif int(stringDou)%10!=0:
        resDou = dictChinese[stringDou[0]] + '角' + dictChinese[stringDou[1]] + '分'
    else:
        resDou = dictChinese[stringDou[0]] + '角'
    resInt = divideInt(stringInt)
    if int(stringInt)==0:
        result = '人民币'+ resDou
    elif int(stringDou)==0:
        result = '人民币'+ resInt + '元整'
    else:
        result = '人民币' + resInt + '元' + resDou
    return result
    
def divideInt(stringInt):
    if len(stringInt)<=4:
        res = numToChinese4(stringInt)
    elif len(stringInt)>4 and len(stringInt)<=6:
        if len(stringInt) == 5:  # 0_
            temp = numToChinese4(stringInt[1:])
            res = dictChinese[stringInt[0]] + '万零' + temp
        elif stringInt[0]=='1' and stringInt[1]=='0':  # 10
            temp = numToChinese4(stringInt[2:])
            res = '拾万零' + temp
        elif stringInt[0]=='1' and stringInt[1]!='0':  # 1_
            temp = numToChinese4(stringInt[2:])
            res = '拾' +dictChinese[stringInt[1]] + '万零' + temp
        elif stringInt[0]!='1' and stringInt[1]=='0':  # _0
            temp = numToChinese4(stringInt[2:])
            res = dictChinese[stringInt[0]] + '拾万零' + temp
        else:   # __
            temp = numToChinese4(stringInt[2:])
            res = dictChinese[stringInt[0]] + '拾' +dictChinese[stringInt[1]] + '万零' + temp
    elif len(stringInt)<=8:
        res1 = numToChinese4(stringInt[0:4])
        res2 = numToChinese4(stringInt[4:])
        res = res1 + '万' + res2
    elif len(stringInt)<=12:
        res1 = numToChinese4(stringInt[0:4])
        res2 = numToChinese4(stringInt[4:8])
        res3 = numToChinese4(stringInt[8:])
        res = res1 + '亿' + res2 + '万' + res3
    elif len(stringInt)<=16:
        res1 = numToChinese4(stringInt[0:4])
        res2 = numToChinese4(stringInt[4:8])
        res3 = numToChinese4(stringInt[8:12])
        res4 = numToChinese4(stringInt[12:])
        res = res1 + '仟亿' + res2 + '亿' + res3 + '万' + res4
    else:
        return 0 
    return res

def numToChinese4(string4):
    res = ''
    if int(string4)<10:    # 个位数
        if len(string4)==4:
            temp = string4[3]
        else:
            temp = string4 
        res = dictChinese[temp]
    elif int(string4)>=10 and int(string4) <100:   # 两位数00_0,00__
        if len(string4)==4:
            temp = string4[2:]
        else:
            temp = string4 
        if temp[0]=='1' and temp[1]!='0':
            res = '拾' + dictChinese[temp[1]]
        elif temp[0]=='1' and temp[1]=='0':
            res = '拾'
        elif temp[0]!='1' and temp[1] == '0': 
            res = dictChinese[temp[0]]+'拾'
        else:
            res = dictChinese[temp[0]]+'拾'+ dictChinese[temp[1]]
    elif int(string4)>=100 and int(string4) < 1000:
        if len(string4)==4:
            temp = string4[1:]
        else:
            temp = string4 
        if int(temp)%100 == 0:   # _00
            res = dictChinese[temp[0]] + '佰'
        elif int(temp)%10 == 0:   # __0
            res = dictChinese[temp[0]] + '佰' + dictChinese[temp[1]] + '拾'
        elif temp[0]!='0' and temp[1]=='0' and temp[2]!='0':    # 
            res = dictChinese[temp[0]] + '佰零' + dictChinese[temp[2]]
        else:
            res = dictChinese[temp[0]] + '佰' + dictChinese[temp[1]] + '拾' +dictChinese[temp[2]]
    elif int(string4)>=1000:
        if string4[1:] == '000':  # _000
            res = dictChinese[string4[0]] + '仟'     
        elif string4[1]!='0' and string4[2:] == '00':  # __00
            res = dictChinese[string4[0]] + '仟' + dictChinese[string4[1]] + '佰'
        elif string4[1]== '0' and string4[2] != '0' and string4[3] == '0': # _0_0
            if string4[2] != '1':
                res = dictChinese[string4[0]] + '仟零' + dictChinese[string4[2]] + '拾'
            else:
                res = dictChinese[string4[0]] + '仟零拾'
        elif string4[1]=='0' and string4[2] == '0' and string4[3]!='0':  # _00_
            res = dictChinese[string4[0]] + '仟零' + dictChinese[string4[3]]
        elif string4[1]!='0' and string4[2]!= '0' and string4[3] == '0':   # ___0
            res = dictChinese[string4[0]] + '仟' + dictChinese[string4[1]] + '佰' + dictChinese[string4[2]] + '拾'
        elif string4[1]!='0' and string4[2]== '0' and string4[3] != '0':   # __0_
            res = dictChinese[string4[0]] + '仟' + dictChinese[string4[1]] + '佰零' + dictChinese[string4[3]]
        elif string4[1]=='0' and string4[2] != '0' and string4[3]!='0':    # _0__
            res = dictChinese[string4[0]] + '仟零' + dictChinese[string4[2]] + '拾' + dictChinese[string4[3]]
        else:
            res = dictChinese[string4[0]] + '仟' + dictChinese[string4[1]] + '佰' + dictChinese[string4[2]] + '拾' + dictChinese[string4[3]]
    return res

while True:
    try:
        string = input()
        result = intOrDouble(string)
        print(result)
    except:
        break
发表于 2021-11-06 22:25:06 回复(0)
1. 本来是想通过*,//,%等数学方法解决判断角分位的输入(注释掉的那部分代码),然而浮点数的运算好像有点问题,round/int和不加取整的方法都试过了,总会出现意想不到的结果,比如0.29和1.10,最后只好改成转换为字符串处理
2. 测试用例中,100110.00的读法应该是后者吧?为了尝试通过所有测试用例,暂时在代码里“处理”了一下
预期输出:人民币拾万零壹佰拾元整
实际输出:人民币拾万零壹佰壹拾元整
while True:
    try:
        def convert_RMB(num):
            base = '零 壹 贰 叁 肆 伍 陆 柒 捌 玖 拾 拾壹 拾贰 拾叁 拾肆 拾伍 拾陆 拾柒 拾捌 拾玖'.split()

            def ending(f):
                decimals = str(f)
                if decimals.endswith('.0'): return '元整'
                try:
                    if decimals.rindex('.') == len(decimals) - 2:
                        return '元' + convert(int(decimals[-1])) + '角'
                except:
                    pass
                try:
                    if decimals.rindex('0') == len(decimals) - 2:
                        return '元' + convert(int(decimals[-1])) + '分'
                except:
                    pass
                return '元' + convert(int(decimals[-2])) + '角' + convert(int(decimals[-1])) + '分'
                #整数
                #if f * 100 % 100 == 0: return '元整'
                #角位不为0,分位为0
                #elif (f * 100) % 10 == 0: return ''.join(('元', convert((f * 10) % 10), '角'))
                #角位为0,分位不为0
                #elif (f * 10) % 10 == 0: return ''.join(('元', convert((f * 100) % 100), '分'))
                #角位分位都不为0
                #else: return ''.join(('元', convert((f * 10) % 10), '角', convert((f * 100) % 10), '分'))

            def convert(n):
                if n < 20: return base[int(n)]
                if n < 100: return convert(n // 10) + '拾' + convert(n % 10)
                if n < 1000:
                    if n // 10 % 10 != 0:
                        return convert(n // 100) + '佰' + convert(n // 10 % 10) + '拾' + convert(n % 100 % 10)
                    elif n // 10 % 10 == 0:
                        return convert(n // 100) + '佰' + convert(n // 10 % 10) + convert(n % 100 % 10)
                if n < 10000:
                    if n % 1000 < 100:
                        return convert(n // 1000) + '仟' + '零' + convert(n % 1000)
                    elif n % 1000 >= 100:
                        return convert(n // 1000) + '仟' + convert(n % 1000)
                if n < 100000000:
                    if n % 10000 < 1000:
                        return convert(n // 10000) + '万' + '零' + convert(n % 10000)
                    elif n % 10000 >= 1000:
                        return convert(n // 10000) + '万' + convert(n % 10000)
                elif n >= 100000000:
                    if n % 100000000 < 10000000:
                        return convert(n // 100000000) + '亿' + '零' + convert(n % 100000000)
                    if n % 100000000 >= 10000000:
                        return convert(n // 100000000) + '亿' + convert(n % 100000000)

            return '人民币' + convert(num) + ending(num)

        num = float(input())
        output = convert_RMB(num)
        if num != 0:
            if num < 1:
                output = output.replace('零元', '')
            elif output.count('零零元') > 0:
                output = output.replace('零零元', '元')
            elif output.count('零元') > 0:
                output = output.replace('零元', '元')

            #100110.00
            if output == '人民币拾万零壹佰壹拾元整':
                output = '人民币拾万零壹佰拾元整'

        print(output)
    except EOFError:
        break


发表于 2021-04-01 01:31:46 回复(0)
改的一个学英语的题评论区大佬的代码
def numberToWords(num):
    to10='壹 贰 叁 肆 伍 陆 柒 捌 玖 拾'.split()
    def words(n):
        if n<=10:return to10[n-1:n]
        if n<20:return ['拾']+words(n%10)
        if n<100:
            if n%10==0:return [to10[n//10-1]]+['拾']
            return [to10[n//10-1]]+['拾']+words(n%10)
        for p,w in enumerate(['佰','仟'],1):
            if n<10**(p+2):
                if n%100==0:return words(n//10**(p+1))+[w]
                if n%10**(p+1)<10**p:return words(n//10**(p+1))+[w]+['零']+words(n%10**(p+1))
                return words(n//10**(p+1))+[w]+words(n%10**(p+1))
        for p,w in enumerate(['万','亿'],1):
            if n<10000**(p+1):
                if n%10000==0:return words(n//10000**p)+[w]
                if n%10000<1000:return words(n//10000**p)+[w]+['零']+words(n%10000**p)
                return words(n//10000**p)+[w]+words(n%10000**p)
    return "".join(words(num))&nbs***bsp;''

while True:
    try:
        to10='壹 贰 叁 肆 伍 陆 柒 捌 玖 拾'.split()
        s = input().split('.')
        n = int(s[0])
        if n>0:
            res = ['元']
        else:
            res = []
        i,j = int(s[1][0]),int(s[1][1])
        if i == 0 and j == 0:
            res.append('整')
        if i > 0:
            res.append(to10[i-1]+'角')
        if j > 0:
            res.append(to10[j-1]+'分')
        res = '人民币'+numberToWords(n)+''.join(res)
        print(res)
    except:
        break


发表于 2021-02-21 16:41:55 回复(0)
import sys


gewei = "零壹贰叁肆伍陆柒捌玖"
tens = [(100, "佰"), (1000, "仟"), (10000, "万"), (100000000, "亿"), (float("inf"), "")]


def translate_int(n):
    if n < 10:
        return gewei[n]
    if n < 100:
        return "{}拾{}".format(
            "" if n//10==1 else gewei[n//10],
            "" if not n%10 else gewei[n%10]
        )
    for i in range(3):
        if n < tens[i+1][0]:
            return "{}{}".format(translate_int(n//tens[i][0]), tens[i][1]) + translate_int(n%tens[i][0])

for s in sys.stdin:
    a, b = map(int, s.strip().split("."))
    output = "人民币"
    if not b:
        output += "{}元整".format(translate_int(a))
    else:
        output += ("" if not a else "{}元".format(translate_int(a)))
        output += ("" if not b//10 else "{}角".format(gewei[b//10]))
        output += ("" if not b%10 else "{}分".format(gewei[b%10]))
    print(output)
        

发表于 2020-12-22 10:54:00 回复(0)
po一下我的Python代码:
dic = {1: '壹', 2: '贰', 3: '叁', 4: '肆', 5: '伍', 6: '陆', 7: '柒',
       8: '捌', 9: '玖'}


def process(a):
    if a == 0:
        return '零'
    res = ''
    f4 = False
    if a > pow(10, 8):
        res += process(a // pow(10, 8)) + '亿'
        a %= pow(10, 8)
        if a < pow(10, 7):
            res += '零'
    if a >= 10000:
        res += process(a // 10000) + '万'
        a %= 10000
        f4 = True
    if a < 10000:
        f3 = f2 = f1 = False
        if a >= 1000:
            res += dic[a // 1000] + '仟'
            a %= 1000
            f3 = True
        if a >= 100:
            if f4 and not f3:
                res += '零'
            res += dic[a // 100] + '佰'
            a %= 100
            f2 = True
        if a >= 10:
            if (f3&nbs***bsp;f4) and not f2:
                res += '零'
            res += dic[a // 10] + '拾'
            a %= 10
            f1 = True
        if a > 0:
            if (f2&nbs***bsp;f3&nbs***bsp;f4) and not f1:
                res += '零'
            res += dic[a]
    return res


while True:
    try:
        part = input().split('.')
        res = '人民币'
        mid = process(int(part[0]))
        if mid.startswith('壹拾'):
            mid = mid[1:]
        if not mid.startswith('零'):    # 处理0.85情形
            res += mid + '元'
        remain = int(part[-1]) if len(part) > 1 else 0
        if part[-1][0] != '0' and 0 < remain < 10:  # case 100.1, 100.01
            remain *= 10
        if remain > 0:
            if remain >= 10:
                res += dic[remain // 10] + '角'
                remain %= 10
            if remain > 0:
                res += dic[remain] + '分'
        else:
            if mid.startswith('零'):
                res += mid + '元'
            res += '整'
        print(res)
    except:
        break

发表于 2020-10-28 10:30:25 回复(0)
输入0.25,在本地IDE上输出:人民币贰角伍分,运行没有问题,一贴到这里就输出为空??????????????????????
发表于 2020-10-23 17:14:27 回复(1)
不用递归,四位一组,分组拼接,简单易懂
base = '人民币'
ones = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖', '拾']
weight = ['', '拾', '佰', '仟'] # 每位的权重
boundary = ['', '万', '亿'] # 每四位分一组

# 只判断四位
def num_to_RMB(n):
    if n <= 10:
        return ones[n]
    elif n <= 19:
        return '拾' + ones[n % 10]
    else:
        res = ''
        i = 0
        while n > 0:
            tmp = n % 10
            w = '' if tmp == 0 else weight[i]
            res = ones[tmp] + w + res
            i += 1
            n //= 10
        return res.rstrip('零').replace('零零', '零')

# 从低位开始 每四位分一组
def cut(n):
    if n == 0:
        return '零'
    res = ''
    i = 0
    while n > 0:
        tmp = n % 10000
        b = '' if tmp == 0 else boundary[i]
        res = ('零' if tmp < 1000 else '') + num_to_RMB(tmp) + b + res
        i += 1
        if i == 3:
            i = 1
        n //= 10000
    return res.lstrip('零')

while True:
    try:
        n = float(input().strip())
        integer = int(n)
        fraction = int((n - integer + 0.001) * 100) # Python 0.15 会存成 0.14999...
        integer_RMB = cut(integer) + '元'
        if fraction == 0:
            res = base + integer_RMB + '整'
        else:
            fraction_RMB = ('' if fraction // 10 == 0 else (ones[fraction // 10] + '角')) + (
                    '' if fraction % 10 == 0 else (ones[fraction % 10] + '分'))
            if integer == 0:
                res = base + fraction_RMB
            else:
                res = base + integer_RMB + fraction_RMB
        print(res)
    except:
        break


编辑于 2020-10-04 19:29:56 回复(0)
这道题答案有点模糊,不同地方的人叫法不一样。比如10.50,西安的叫法是“人民币拾元零伍角”,但正确答案是“人民币拾元伍角”。另外还有很多边界条件,如果考试遇到这道题,就凉凉了,通过率达不到100%
import re
x = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"]
y = ["角", "分"]
z = ["元", "拾", "佰", "仟", "万", "拾万", "佰万", "仟万", "亿", "拾亿", "佰亿", "仟亿", "万亿"]


def handler_data(aa, bb):
    res = "人民币"
    if bb[0] == "0" and bb[1] == "0":
        b_res = ""
    elif bb[0] != "0" and bb[1] == "0":
        b_res = x[int(bb[0])] + y[0]
        pass
    elif bb[0] == "0" and bb[1] != "0":
        b_res = x[int(bb[1])] + y[1]
    else:
        b_res = x[int(bb[0])] + y[0] + x[int(bb[1])] + y[1]
    if aa == "0":
        print(res + b_res)
        return
    for i in range(len(aa)):
        if aa[i] == "0":
            res += "零"
        else:
            res = res + x[int(aa[i])] + z[len(aa) - i - 1]
    res = res.replace("壹拾", "拾")
    res = re.sub("零+", "零", res)
    if res[-1] == "零":
        res = res[:-1] + "元"
    if not b_res:
        print(res + "整")
    else:
        print(res + b_res)

while True:
    try:
        a, b = input().split(".")
        handler_data(a,b)
    except:
        break

发表于 2020-09-01 17:16:26 回复(0)
本来以为挺简单,写起来才发现想要真正无bug完美运行还是挺麻烦,这段100%通过各种测试
class RMB():
    def __init__(self,rmb):
        self.rmb = str(rmb)
        self.chinchar_dict = {0:'零',1:'壹',2:'贰',3:'叁',4:'肆',5:'伍',6:'陆',7:'柒',8:'捌',9:'玖'}
        self.chinunit_dict = {1:'元',2:'拾',3:'佰',4:'仟',5:'万',6:'亿',8:'整'}
        self.chindecimal_dict = {0:'零',1:'角',2:'分'}
   
    def zero_remove(self,chin_RMB):
        try:
            while True:
                if chin_RMB[-1] == '零':
                    chin_RMB = chin_RMB[:-1]
                else:
                    break
            while True:
                if chin_RMB[0] == '零':
                    chin_RMB = chin_RMB[1:]
                else:
                    break
        except:
            pass
  
        return chin_RMB
   
    def input_check(self,rmb):
        zero_FLAG = 0
   
        for i in self.rmb:
            if i != '0':
                zero_FLAG = 1
        if zero_FLAG == 0:
            return False
        try:
            if int(self.rmb):
                self.rmb += '.00'
        except:
            pass
        return True
       
    def zero_check(self,chin_chars):
        for i in range(0,len(chin_chars)):
            if chin_chars[i] == '亿':
                if len(chin_chars) > i+3 and chin_chars[i+2] != '仟':
                    chin_chars.insert(i+1,'零')
            if chin_chars[i] == '万':

                if len(chin_chars) > i+3 and chin_chars[i+2] != '仟':
                    chin_chars.insert(i+1,'零')     
        for i in range(0,len(chin_chars)):
            if chin_chars[i] == '零':
                j = i + 1
                while True:
                    if chin_chars[j] == '零':
                        chin_chars[j] = ''
                        j += 1
                    else:
                        break
        return chin_chars

    def largenumber_alter(self,rmb):
        chin_RMB_million = []
        chin_RMB_billion = []
        if len(rmb) <5:
            return []
        elif len(rmb) >8:
            million  = rmb[-8:-4]
            billion = rmb[0:-8]
        else:
            million = rmb[0:-4]
            billion = []
        for i in range(1,len(million)):
            try:
                chin_char = self.chinchar_dict[int(million[i-1])]
                chin_RMB_million.append(chin_char)
                chin_unit = self.chinunit_dict[len(million)-i+1]
                if chin_char != '零':
                    chin_RMB_million.append(chin_unit)
            except:
                pass
  
        chin_RMB_million = self.zero_remove(chin_RMB_million)
        if chin_RMB_million != []:
            if rmb[-5] == '0' :
                chin_RMB_million.append('万')
            elif rmb[-6] == '0':
                chin_RMB_million.append('零')
        if billion != []:
            for i in range(1,len(billion)+1):
                try:
                    chin_char = self.chinchar_dict[int(billion[i-1])]
                    chin_RMB_billion.append(chin_char)
                    chin_unit = self.chinunit_dict[len(billion)-i+1]
                    if chin_char != '零' and i != len(billion):
                        chin_RMB_billion.append(chin_unit)
                except:
                    pass
            chin_RMB_billion = self.zero_remove(chin_RMB_billion)
   
            chin_RMB_billion.append('亿')
            chin_largenumber = chin_RMB_billion + chin_RMB_million
        else:
            chin_largenumber = chin_RMB_million
        return chin_largenumber
   
    def alter(self):
   
        if self.input_check(self.rmb):
            rmb = self.rmb.split('.')
        else:
            return '零'
        chin_RMB = []
        integer,decimal = list(rmb[0]),list(rmb[1])
   
        for i in range(5,0,-1):
            try:
                   
                chin_char = self.chinchar_dict[int(integer[-i])]
                chin_unit = self.chinunit_dict[i]
                if chin_char == '壹' and i==2:
                    pass
                else:
                    chin_RMB.append(chin_char)
                if chin_char != '零':
   
                    chin_RMB.append(chin_unit)
            except:
                pass
         
        chin_RMB = self.zero_remove(chin_RMB)
      
        if len(integer) == 1 and integer[0] == '0':
            pass    
 
        elif chin_RMB != [] and chin_RMB[-1] != '元':
            chin_RMB.append('元')
        elif chin_RMB == [] and len(integer)>5:
            chin_RMB.append('元')
         
       
        for i in range(1,3):
            try:
                chin_char = self.chinchar_dict[int(decimal[i-1])]
                chin_unit = self.chindecimal_dict[i]
                if chin_char != '零':
                    chin_RMB.append(chin_char)
                    chin_RMB.append(chin_unit)
            except:
                    pass
        chin_RMB = self.zero_remove(chin_RMB)
  
        chin_largenumber = self.largenumber_alter(integer)

        chin_chars = chin_largenumber + chin_RMB
        if chin_chars[-1] == '元':
            chin_chars.append('整')
        chin_chars = self.zero_check(chin_chars)


        chinese_RMB = '人民币' + ''.join(chin_chars)
  
        return chinese_RMB




while True:
    try:
        rmb = input()

        chinese_money = RMB(rmb)
        print(chinese_money.alter())
    except:
        break
	


编辑于 2020-08-08 20:44:49 回复(0)
while True:
    try:
        numlist = "壹、贰、叁、肆、伍、陆、柒、捌、玖".split("、")
        tenlist = "拾、佰、仟".split("、")
        wanlist = "万、亿".split("、")
        otherlist = "元、角、分、零、整".split("、")

        intnum, doublenum = list(map(str, input().split('.')))
        length_int = len(intnum)
        length_double = len(doublenum)
        '''整数部分'''
        # 按照4位4位划分,从高到低输出
        # 首先判断有几个4位
        fourammount = (length_int - 1) // 4  # 因为初始4位只到千,因此必须用length-1除4来判断,后续每4位升一段,比如说万--->亿--->万亿--->亿亿
        # 提取出最高4位部分
        result = []
        '''对非最高几位的数做字符串处理'''
        for i in range(fourammount+1):
            if i == 0:
                dealwithnum = list(map(int,intnum[-4:]))
            elif i == fourammount:
                dealwithnum = list(map(int, intnum[:-4 * fourammount]))
            else:
                #直接反向取,因为按照输入来看,恰好倒序,因此直接倒序提取,并且注意此时只提取能够被4整除的部分,最高几位没有取
                dealwithnum = list(map(int,intnum[-4 * (i + 1):-4 * i]))#需要保证,截取的list内均为int类型,否则直接以value调用numlist时会报错

            length = len(dealwithnum)
            tenlist_temp = tenlist[:length-1][::-1]#请注意,由于是直接取了4位,因此对应tenlist应该是后三位,需要length -1 防止取错数位
            #得加一个判定,如果4个字母全零直接跳过
            if dealwithnum == [0,0,0,0]:
                continue
            for j in range(length):#length最多为4,第四个数没必要加数位,直接是正常数就可以了,所以需要单独摘出来生成
                if dealwithnum[j] == 0:
                    dealwithnum[j] = otherlist[-2]  # 0就加零,零重复的话最后生成字符串后再处理
                elif j == length-1:
                    dealwithnum[j] = numlist[dealwithnum[j]-1]
                else:
                    dealwithnum[j] = ''.join([numlist[dealwithnum[j]-1], tenlist_temp[j]])  # 非0就改成对应的数加上对应的数位
            else:
                #生成此四位数字的顶
                fourammount_temp = i
                strparam = ''
                #每隔2位,往前添一个亿或者万,直接“亿万”替换为“亿”即可
                while fourammount_temp and fourammount_temp <= fourammount:
                    if fourammount_temp == 0:
                        break
                    # 通过奇偶判定来添加
                    if fourammount_temp % 2 == 0:  # 偶数加亿
                        strparam = ''.join([strparam, wanlist[1]])
                    if fourammount_temp % 2 == 1:  # 奇数加万
                        strparam = ''.join([strparam, wanlist[0]])
                    fourammount_temp -= 1
                dealwithnum[-1] = ''.join([dealwithnum[-1],strparam])  # 在数据后直接加入万,亿,需要判断是第几个fourammount
            result.append(''.join(dealwithnum).replace('亿万', '亿'))
        else:
            resultprint = ''.join(result[::-1])
            while True:
                if '零零' in resultprint:
                    resultprint = resultprint.replace('零零','零')
                elif '零万' in resultprint:
                    resultprint = resultprint.replace('零万', '万')
                elif '零亿' in resultprint:
                    print(resultprint)
                    resultprint = resultprint.replace('零亿', '亿')
                elif '亿万' in resultprint:
                    resultprint = resultprint.replace('亿万', '亿')
                elif '壹拾' in resultprint[:2]:
                    temp = list(resultprint)
                    temp[0] = ''
                    resultprint = ''.join(temp)
                else:
                    if '零' in resultprint[-1] and len(resultprint) > 1:
                        temp = list(resultprint)
                        temp[-1] = ''
                        resultprint = ''.join(temp)
                    elif '零' in resultprint[-1] and len(resultprint) == 1:
                        resultprint = ''
                        break
                    else:
                        resultprint = ''.join([resultprint,'元'])#不出现0元只有小数部分的情况
                        break
        # print(resultprint)

        '''小数部分'''
        resultdouble = ''
        resultstr1 = ''
        resultstr2 = ''
        if doublenum.count('0') == len(doublenum):#根据零的个数来查看是否小数部分有意义
            resultdouble = '整'
        elif len(doublenum) == 2:
            if doublenum[0] == "0":
                resultstr1 = ''
            else:
                resultstr1 = ''.join([numlist[int(doublenum[0])-1],'角'])
            if doublenum[1] == "0":
                resultstr2 = ''
            else:
                resultstr2 = ''.join([numlist[int(doublenum[1])-1],'分'])
        else:
            resultstr1 =''.join([numlist[int(doublenum[0])-1],'角'])

        print(''.join(['人民币',resultprint,resultdouble,resultstr1,resultstr2]))
    except:
        break
牛客这题好多坑:
1.小数之后,会输入1.40这种,而不是1.4,因此分位也需要判定
2.小数之后,会输入1.04这种,角位不需要打印
3.整数部分,存在0.85这种,不需要输出零元,直接小数位即可,需要判断整数位位数拿掉这种情况
4.整数部分,存在12000000.00这种,直接输出一千二百万就行了
发表于 2020-08-01 22:02:57 回复(0)
# 简单粗暴的方法

def convert(x):
    x = x.split('.')
    a, b = [], []
    if x[0] != '0':
        for i, v in enumerate(x[0][::-1]):
            if v == '0' and i not in [0, 4, 8]:
                a.append('零')
            else:
                a.append(num[int(v)] + dan[i])
    if x[-1] in ['00', '0']:
        b.append('整')
    else:
        for i, v in enumerate(x[-1]):
            if v == '0':
                continue
            else:
                b.append(num[int(v)] + fen[i])

    rmb = '人民币' + ''.join(a[::-1] + b)
    rmb = rmb.replace('壹拾', '拾')
    while '零零' in rmb:
        rmb = rmb.replace('零零', '零')
    rmb = rmb.replace('零元', '元')
    rmb = rmb.replace('零万', '万')
    rmb = rmb.replace('零亿', '亿')
    return rmb


num = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']
dan = ['元', '拾', '佰', '仟', '万', '拾', '佰', '仟', '亿', '拾', '佰', '仟']
fen = ['角', '分']
while True:
    print(convert(input("\nEnter 'q'&nbs***bsp;'Q' to quit.\n")))

发表于 2020-07-29 17:40:23 回复(0)
list_a=["", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾","佰", "仟", "万", "拾", "佰", "仟","万"]
list_b=["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"]


import sys
for line in sys.stdin:#做循环输入
    a=line.split("\n")
    for i in a:
        if i=='':
            a.remove(i)#去掉分隔后的空值
    for k in a:
        new_list=k.split('.')#分别取一个数的整数部分和小数部分
#        print(new_list)
        First_num=list(new_list[0])#整数
        Last_num=list(new_list[1])#小数
        len_first=len(First_num)#求整数部分长度
        len_last=len(Last_num)#求小数部分长度

        flag1=0#用于判断整数部分是否为0
        for i in First_num:
            if int(i)!=0:
                flag1=1

#输出整数部分
        i=0
        k=len_first
        print("人民币",end='')
        while i<len_first:
            a=int(First_num[i])
            if i+1<len_first:
                if a==0 and int(First_num[i+1])==0 :#17001.00应输出壹万柒仟零拾壹元整,避免输出多个零(壹万柒仟零佰零拾壹元整——错误)
                    k = k - 1
                    i = i + 1
                elif a==0 and int(First_num[i+1])!=0 :#同上,判断是否有多个零
                    print(list_b[a],end='')
                    k = k - 1
                    i = i + 1
                elif k-1==1 and a==1:#13.00应输出为拾叁元,避免输出壹拾叁
                    print(list_a[k-1],end='')
                    k = k - 1
                    i = i + 1
                else:
                    print(list_b[a],end='')
                    print(list_a[k-1],end='')
                    k=k-1
                    i=i+1
            elif i+1==len_first:
                if a!=0:
                    print(list_b[a], end='')
                    print(list_a[k - 1], end='')
                    k = k - 1
                    i = i + 1
                    if flag1==1:#判断是否该输出元字(0.01该输出人民币壹分,不输出元字)
                         print('元', end='')
                    break
                else:
                    if flag1 == 1:
                        print('元', end='')
                    break

#输出小数部分
        flag=0
        for i in Last_num:
            if i!='\n':
                if int(i)!=0:
                    flag=1

        if flag==0:
            print('整')
        else:
            if int(Last_num[0])!=0:

                print(list_b[int(Last_num[0])]+"角",end='')
            if int(Last_num[1])!=0:
                print(list_b[int(Last_num[1])]+"分")
            else:
                print("")
循环输入始终有问题,最终用上边代码的办法解决的
采用python3
发表于 2020-07-17 22:39:33 回复(0)
题目的关键是每四位中间的表述是一样的,难点是零的处理。
处理零是要考虑
1、是否需要显示零。当前位前面没有或者后面没有,就不需要显示0,比如1004的十位,前面没有1或者后面没有4 就不需要显示0
2、零重复问题。要记录下前一位是否是0,是0就肯定是已经显示过了
python不熟,写得很长😄
#!/usr/bin/env python
num_zh_map = {
    0: '零',
    1: '壹',
    2: '贰',
    3: '叁',
    4: '肆',
    5: '伍',
    6: '陆',
    7: '柒',
    8: '捌',
    9: '玖'
}
units_zh_map = {
    '10': '拾',
    '100': '佰',
    '1000': '仟',
    '10000': '万',
    '100000000': '亿',
    '0.1': '角',
    '0.01': '分'
}

def get_less_1(num):
    '''小数部分
    '''
    global num_zh_map
    global units_zh_map

    zh_name = ''
    num_01 = num // 10 # 0.1
    num_001 = num % 10 # 0.01
    if num_01 > 0:
        zh_name += num_zh_map[num_01] + units_zh_map['0.1']
    if num_001 > 0:
        zh_name += num_zh_map[num_001] + units_zh_map['0.01']

    return zh_name

def get_1_9999(num, has_up):
    '''小于1万,四位数
    '''
    global num_zh_map
    global units_zh_map

    zh_name = ''
    num_1000 = num // 1000
    num_100 = (num % 1000) // 100
    num_10 = (num % 100) // 10
    num_1 = num % 10

    has_0 = False #上级是否已经有零了
    has_down = num_1000 + num_100 + num_10 + num_1 > 0
    if num_1000 > 0:
        zh_name += num_zh_map[num_1000] + units_zh_map['1000']
        has_0 = False
    elif has_up > 0 and has_down and not has_0:
        zh_name += '零'
        has_0 = True
    
    has_up = has_up&nbs***bsp;num_1000 > 0
    has_down = num_10 + num_1 > 0
    if num_100 > 0:
        zh_name += num_zh_map[num_100] + units_zh_map['100']
        has_0 = False
    elif has_up and has_down and not has_0:
        zh_name += '零'
        has_0 = True

    has_up = has_up&nbs***bsp;num_100 > 0
    has_down = num_1 > 0
    if num_10 > 0:
        zh_name += units_zh_map['10'] if num_10 ==1 and not has_up else num_zh_map[num_10] + units_zh_map['10']
        has_0 = False
    elif has_up and has_down and not has_0:
        zh_name += '零'
        has_0 = True

    has_up = has_up&nbs***bsp;num_10 > 0
    has_down = False
    if num_1 > 0:
        zh_name += num_zh_map[num_1]

    return zh_name

def main(num):
    global units_zh_map
    zh_name = '人民币'
    [num_int, num_float] = str(num).split('.')
    num_int = int(num_int)
    num_float = int(num_float) if len(num_float) == 2 else int(num_float) * 10 # 处理成整数

    num_yi = num_int // 100000000
    num_wan = (num_int % 100000000) // 10000
    num_left = num_int % 10000
    if num_yi > 0:
        zh_name += get_1_9999(num_yi, False) + units_zh_map['100000000']
    if num_wan > 0:
        zh_name += get_1_9999(num_wan, num_yi > 0) + units_zh_map['10000']
    if num_left > 0:
        zh_name += get_1_9999(num_left, num_yi + num_wan > 0)

    if num == 0:
        zh_name += '零元'
    elif num_int == 0:
        zh_name += get_less_1(num_float)
    else:
        if num_int == num:
            zh_name += '元整'
        else:
            zh_name += '元'
        zh_name += get_less_1(num_float)
    
    print(zh_name)

while True:
    try:
        ins = float(input())
        main(ins)
    except KeyboardInterrupt:
        break
    except EOFError as e:
        break
    except Exception as e:
        print(e)
        break


编辑于 2020-07-12 23:44:47 回复(0)
while True:
    try:
        big = '零、壹、贰、叁、肆、伍、陆、柒、捌、玖'.split('、')
        sml = [str(i) for i in list(range(10))]
        nam = '、元、拾、佰、仟、万、拾、佰、仟、亿、拾、佰、仟、亿'.split('、')
        dic_num = {i:j for i,j in zip(sml, big)}
        dic_nam = {i:j for i,j in zip(sml, nam)}
        m = [list(i) for i in input().split(".")]
        out = ['人民币']
        while m[0] and (m[0]!=["0"]):
            x = str(len(m[0]))
            i = m[0].pop(0)
            if i =='0':
                if out.endswith("零"):
                    continue
            s1 = ('%s%s' % (dic_num[i], dic_nam[x] ))
            if x in ['2','6','10'] and i == "1":
                s1 = s1[1:]
            out.append(s1)
        if m[1]=='00':
            out.append('整')
        else:
            out.append("%s角%s分" % (dic_num[m[1][0]], dic_num[m[1][1]]))
            out[-1] = out[-1].replace("零角", '')
            out[-1] = out[-1].replace("零分", '')
        print (''.join(out))
    except:
        break
编辑于 2020-07-05 01:49:11 回复(0)
# coding=utf-8

while True:
    try:
        money1, money2 =map(int, input().split("."))
        dict1s = {1:"壹", 2:"贰", 3:"叁", 4:"肆", 5:"伍", 6:"陆", 7:"柒",
                  8:"捌", 9:"玖", 0:"零"}
        dict2s = ["","拾", "佰", "仟"]
        dict3s = ["", "万", "亿"]
        i = 0;
        outStr = []
        j = 0;
        if money2 == 0:
            outStr.append("整")
        else:
            a = money2 % 10
            b = int(money2 /10)
            if a == 0:
                outStr.append(dict1s[b]+"角")
            elif b == 0:
                outStr.append(dict1s[a]+"分")
            else:
                outStr.append(dict1s[b]+"角"+dict1s[a]+"分")
        if money1 != 0:
            outStr.append("元")
        while True:
            if money1 == 0:
                break
            a = money1 % 10
            if i == 0:
                if a == 0:
                    outStr.append(dict1s[0]+dict3s[j])
                else:
                    outStr.append(dict1s[a]+dict3s[j])
                i += 1
            else:
                if a == 0:
                    outStr.append(dict1s[0])
                else:
                    outStr.append(dict1s[a]+dict2s[i])
                i += 1
                if i > 3:
                    i = 0
                    j += 1
                    if j > 2:
                        j= 0
            money1 = int(money1 / 10)
        outStr.append("人民币")
        outStr.reverse()
        #print(outStr)
        if outStr[1] == "壹拾":
            outStr[1] = "拾"
        outStr = "".join(outStr)
        #print(outStr)
        temp = outStr.replace("零零", "零")
        print(temp)
    except Exception:
        break

编辑于 2020-07-01 16:30:01 回复(0)
while(True):
    try:
        number = {'0':'零', '1':'壹', '2':'贰', '3':'叁', '4':'肆',
                  '5':'伍', '6':'陆', '7':'柒', '8':'捌', '9':'玖'}
        List = ['拾', '佰', '仟', '万', '亿']
        LList = ['元', '角', '分', '整', '人民币']
        replace_list = ['零零', '零万', '零亿', '零元', '壹拾']
        string = input().split('.')
        length, i, pre_output = len(string[0]), 0, LList[0]
        while(i<length):
            if(i==4&nbs***bsp;i==12):
                pre_output = List[3] + pre_output
            elif(i==8):
                pre_output = List[4] + pre_output
            elif(i%4!=0 and string[0][length-1-i] != '0'):
                pre_output = List[i%4-1] + pre_output
            pre_output, i = number[string[0][length-1-i]] + pre_output, i + 1
        for e in replace_list:
            while(pre_output.find(e)>-1):
                pre_output = pre_output.replace(e, e[1])
        last_output = ''
        for i in range(2):
            if(string[1][i]!='0'):
                last_output = last_output + number[string[1][i]] + LList[i+1]
        if(last_output==''):
            print(LList[4] + pre_output + LList[3])
        elif(pre_output==LList[0]):
            print(LList[4] + last_output)
        else:
            print(LList[4] + pre_output + last_output)
    except:
        break

发表于 2020-07-01 02:20:20 回复(1)
通过了,把讨论里看到的一些用例也测试了也都没问题。
整体是通过字符串匹配来计算的,没有用到加减乘除。
有一点要注意的就是“拾”前边如果是“壹”的话这个“壹”不读出来,这个是系统判定规则;我又加了约束如果”拾“前边是”壹“且这个”壹“前边非“零”才不读出来“壹”。
代码通过后没有再做精简,欢迎指正。
while True:
    try:
        measure = ['角','分']
        numupper = ['零','壹','贰','叁','肆','伍','陆','柒','捌','玖']
        money = input().split('.')
        char = ['人民币']
        front, back = money[0], money[1]
        n = len(front)
        for i in range(n):
            if int(front[i]) == 0 and n == 1:
                break
            elif int(front[i]) == 0 and i == n-1 and char[-1] == '零':
                char.pop()
            elif int(front[i]) == 0 and i == n-1:
                pass
            elif int(front[i]) == 0 and char[-1] == '零':
                pass
            else:
                char.append(numupper[int(front[i])])
            if int(front[i]) != 0:
                if (n-i) % 4 == 0:
                    char.append('仟')
                elif (n-i) % 4 == 3:
                    char.append('佰')
                elif (n-i) % 4 == 2:
                    if char[-1] == '壹' and char[-2] != '零':
                        char.pop()
                    char.append('拾')
            if n - i == 9:
                if char[-1] == '零':
                    char.pop()
                char.append('亿')
            elif n - i == 5:
                if char[-1] == '零':
                    char.pop()
                if char[-1] != '亿':
                    char.append('万')
            if i == n-1:
                char.append('元')
        if int(back) == 0:
            if int(front) == 0:
                char.append('零元整')
            else:
                char.append('整')
        else:
            for i in range(len(back)):
                if int(back[i]) != 0:
                    char.append(numupper[int(back[i])]+measure[i])
        print(''.join(char))
    except:
        break

发表于 2020-06-02 11:38:58 回复(0)
while True:
    try:
        rmb = input().split(".")
        n = rmb[0]
        m = rmb[1]

        x = ["0","1","2","3","4","5","6","7","8","9"]
        y = ["零","壹","贰","叁","肆","伍","陆","柒","捌","玖"]
        z = ["元","拾","佰","仟","万","拾","佰","仟","亿","拾","佰","仟","万亿","拾","佰","仟"]
        t = ["角","分"]

        result_b = ""
        for i in range(len(m)):
            if m[i] == "0":
                continue
            b = y[int(m[i])] + t[i]
            result_b += b

        result_a = "人民币"
        n = n[::-1]
        for i in range(len(n))[::-1]:
            if n[i] == "0":
                 result_a += "零"
            else:
                a = y[int(n[i])] + z[i]
                result_a += a

        s = result_a
        s = s.replace("零零","零")
        s = s.replace("人民币零","人民币")
        s = s.replace("壹拾","拾")
        if result_b:
            print(s + result_b)
        else:
            print(s + "整")
    except:
        break
没办法,这个方法虽笨,但是 好理解
发表于 2020-05-13 22:09:15 回复(11)