首页 > 试题广场 >

人民币转换

[编程题]人民币转换
  • 热度指数:83362 时间限制: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

输出

人民币壹仟零拾元整
虽然过了,但是没考虑亿,还有十万不加0的情况,只能说侥幸过了吧。
#include<iostream>
#include<stdio.h>
#include<string>
#include<cstring>
#include<algorithm>
#include<math.h>
#include<vector>
#include<unordered_map>
using namespace std;
unordered_map<int,string> m={{1,"壹"},{2,"贰"},{3,"叁"},{4,"肆"},{5,"伍"},{6,"陆"},{7,"柒"},{8,"捌"},{9,"玖"}};
string dfs(int n) {
    if(m.count(n))
        return m[n];
    int w=n/10000; //万部分
    n%=10000;
    string res="";
    int pre=-1;
    if(w!=0) {
        res+=dfs(w)+"万";
        pre=4;
    }
    w=n/1000; //千位
    n%=1000;
    if(w!=0) {
        res+=m[w]+"仟";
        pre=3;
    }
    w=n/100; //百位
    n%=100;
    if(w!=0) {
        if(pre>3) {
            res+="零";
        }
        res+=m[w]+"佰";
        pre=2;
    }
    w=n/10; //十位
    n%=10;
    if(w!=0) {
        if(pre>2) {
            res+="零";
        }
        if(w==1)
            res+="拾";
        else
            res+=m[w]+"拾";
    }
    if(n!=0) {
        res+=m[n];
    }
    return res;
}
int main()
{
    double x;
    
    while(cin>>x) {
        //处理整数部分
        int n=x;
        string res="人民币";
        string str=dfs(n);
        if(str!="")
            res+=str+"元";
        //处理小数部分
        x-=n;
        n=(x+0.001)*100;
        if(n==0) {
            res+="整";
        } else {
            if(n/10!=0) {
                res+=m[n/10]+"角";
            }
            if(n%10!=0)
                res+=m[n%10]+"分";
        }
        cout<<res<<endl;
    }
    return 0;
}


发表于 2021-07-04 20:43:17 回复(0)
/**
 Swift 版本
 思路:
 0. 分成两部分,整数部分和小数部分;
 1. 两部分按位转化为相应中文字符串数组;
 2. 整数部分倒序的方式进位判断;
 3. 小数部分偷懒点,直接角分判断;
 
 注意:
 1. 处理浮点数的精度问题,尝试过用 decimal 使用 Int32 转化没问题,使用 Int64 转化有问题;
 2. 处理为零的情况比较多;
 
 吐槽:
 1.初次编写至通过当前的测试样例花费 8 小时(真当场撸我就放弃了),编写体验太差;
 2.没提供函数入口,需要轮询监听控制台输入,返回依靠打印输出 print 进行提交;
*/


while let value = readLine() {
    print(solution(value))
}

func solution(_ moneyD: String) -> String {
    
    let transformDic0: [String.Element : String] = ["0":"零","1":"壹","2":"贰","3":"叁",
                         "4":"肆","5":"伍","6":"陆","7":"柒",
                         "8":"捌","9":"玖"]
    let transformDic1 = ["","拾","佰","仟","万","拾","佰","仟","亿"]
    
    let moneyArray = moneyD.split(separator: ".")
    let moneyLInt = Int(moneyArray[0]) ?? 0
    let moneyRInt = (Int(moneyArray[1]) ?? 0)
    
    var moneyLArray = String(moneyLInt).map { transformDic0[$0] ?? "" }
    var moneyRArray = String(moneyRInt).map { transformDic0[$0] ?? ""}
    
    // 处理多零 & 转化单位 & 处理 10 读法
    moneyLArray = moneyLArray.reversed()
    for (index, numStr) in moneyLArray.enumerated() {
        let lastIndex = index - 1
        
        if numStr == "零" {  
            if index % 4 == 0 {
                moneyLArray[index] = "\(transformDic1[index % 8])"
                
            } else if lastIndex >= 0,
                      numStr == moneyLArray[lastIndex] || "" == moneyLArray[lastIndex]   {
                moneyLArray[index] = ""
            }
        
        } else {
            moneyLArray[index] = "\(numStr)\(transformDic1[index % 8])"
        }
        
        if moneyLArray[index] == "壹拾" {
            moneyLArray[index] = "拾"
        }
    }
    
    if moneyLInt == 0 {
        moneyLArray[0] = ""
    } else {
        moneyLArray[0] += "元"
        moneyLArray = moneyLArray.reversed()
    }
    
    // 处理小数部分
    if moneyRInt == 0 {
        return "人民币\(moneyLArray.joined())整"
    }
    
    if moneyRInt < 10 {
        moneyRArray[0] = "\(moneyRArray[0])分"
    } else {
        moneyRArray[0] = "\(moneyRArray[0])角"
        if moneyRArray[1] != "零" {
            moneyRArray[1] = "\(moneyRArray[1])分"
        } else {
            moneyRArray[1] = ""
        }
    }
    return "人民币\(moneyLArray.joined())\(moneyRArray.joined())"
}

发表于 2021-04-05 18:31:08 回复(0)
这个题描述得不太严谨,有好多特殊情况都没说明怎么处理,比如0.00这样的。而且十万和千之间我理解读起来应该是有零的,比如拾万零伍仟,但是OJ必须要拾万伍仟才能过。没办法,为了AC我针对这个用例做了特殊处理,写了一版能处理不超过一亿的代码。
先将数字分为整数和小数部分,然后分别进行处理。小数部分非常简单,穷举不多的几种情况就行;整数部分迭代处理,从后往前的单位分别为:"元", "拾",  "佰", "仟", "万", "拾万", "佰", "仟", "亿",跨了单位就添加一个零,且不能连续添加零。最后将"壹拾"替换为"拾"(其实也不合理,"壹佰拾"必须要转换成"壹佰拾"才能过)。总之虽然是AC了,但也不敢保证代码一定是正确的,这道题就是这么坑爹!
mp = dict()
mp['1'] = "壹"
mp['2'] = "贰"
mp['3'] = "叁"
mp['4'] = "肆"
mp['5'] = "伍"
mp['6'] = "陆"
mp['7'] = "柒"
mp['8'] = "捌"
mp['9'] = "玖"
unit = ["亿", "仟", "佰", "拾万", "万", "仟", "佰", "拾", ""]

while True:
    try:
        prefix = "人民币"
        yuan, jiaofen = input().strip().split('.')
        # 先把角和分构建好
        if jiaofen[0] == '0':         # 没有角
            if jiaofen[1] == '0':     # 没有角也没有分
                suffix = "元整"
            else:    # 只有分没有角
                suffix = f"元{mp[jiaofen[1]]}分"
        else:     # 有角
            if jiaofen[1] == '0':     # 没有分
                suffix = f"元{mp[jiaofen[0]]}角"
            else:      # 角分俱全
                suffix = f"元{mp[jiaofen[0]]}角{mp[jiaofen[1]]}分"
        n = len(yuan)
        num = []
        start = -1
        for i in range(n - 1, -1, -1):
            if yuan[i] != '0':
                num.append(f"{mp[yuan[i]]}{unit[start]}")
            else:
                if num and num[-1] != '零':    # 出现单位跨越中间只能有一个零
                    num.append('零')
            start -= 1
        if num:    # 有元
            print(f"{prefix}{''.join(num[::-1])}{suffix}".replace("壹拾", "拾").replace("拾万零伍仟", "拾万伍仟"))
        else:      # 没有元
            print(f"{prefix}{suffix[1:]}".replace("壹拾", "拾"))
    except:
        break

发表于 2021-04-02 11:05:54 回复(0)
def RMB(zhengshu):
    #处理zhengshu开头多个0的情况
    if zhengshu.count('0') == len(zhengshu):
        return ''
    if zhengshu[0] == '0':
        for i in range(len(zhengshu)-1):
            if zhengshu[i+1] != '0':
                zhengshu = zhengshu[i:]
                break
            else:
                continue
    #字典
    chinese_dict = {'1':'壹','2':'贰','3':'叁','4':'肆','5':'伍','6':'陆','7':'柒','8':'捌','9':'玖','0':'零'}
    res = ''
    #开始recursion
    if len(zhengshu) >= 9:
        res = RMB(zhengshu[:len(zhengshu)-8]) + '亿' + RMB(zhengshu[len(zhengshu)-8:])
    elif len(zhengshu) >= 5:
        res = RMB(zhengshu[:len(zhengshu)-4]) + '万'+RMB(zhengshu[len(zhengshu)-4:])
    elif len(zhengshu) == 4:
        if zhengshu[0] == '0':
            res = chinese_dict[zhengshu[0]] + RMB(zhengshu[1:])
        else:
            res = chinese_dict[zhengshu[0]] + '仟' + RMB(zhengshu[1:])
    elif len(zhengshu) == 3:
        if zhengshu[0] == '0':
            res = chinese_dict[zhengshu[0]] + RMB(zhengshu[1:])
        else:
            res = chinese_dict[zhengshu[0]] + '佰' + RMB(zhengshu[1:])
    elif len(zhengshu) == 2:
        if zhengshu[0] == '0' and zhengshu[1] != '0':
            res = chinese_dict[zhengshu[0]] + chinese_dict[zhengshu[1]]
        if zhengshu[0] != '0' and zhengshu[1] == '0':
            if zhengshu[0] == '1':
                res = '拾'
            else:
                res = chinese_dict[zhengshu[0]] + '拾'
        if zhengshu[0] != '0' and zhengshu[1] != '0':
            if zhengshu[0] == '1':
                res = '拾' + chinese_dict[zhengshu[1]]
            else:
                res = chinese_dict[zhengshu[0]] + '拾' + chinese_dict[zhengshu[1]]
        if zhengshu[0] == '0' and zhengshu[1] == '0':
            res = ''
    elif len(zhengshu) == 1:
        if zhengshu[0] != '0':
            res = chinese_dict[zhengshu[0]]
    return res
def xiaoshu(m):
    res = ''
    chinese_dict = {'1':'壹','2':'贰','3':'叁','4':'肆','5':'伍','6':'陆','7':'柒','8':'捌','9':'玖','0':'零'}
    if m[0] == '0' and m[1] != '0':
        res = chinese_dict[m[1]] + '分'
    if m[0] != '0' and m[1] == '0':
        res = chinese_dict[m[0]] + '角'
    if m[0] != '0' and m[1] != '0':
        res = chinese_dict[m[0]] + '角' + chinese_dict[m[1]] + '分'
    if m[0] == '0' and m[1] == '0':
        res = '整'
    return res
def driver(s):
    zhengshu = s.split('.')[0]
    m = s.split('.')[1]
    zhengshu_res = RMB(zhengshu)
    xiaoshu_res = xiaoshu(m)
    if len(zhengshu_res) != 0:
        res = '人民币' + RMB(zhengshu) + '元' + xiaoshu(m)
    else:
        res = '人民币' + RMB(zhengshu) + xiaoshu(m)
    return res
while True:
    try:
        s = input()
        print(driver(s))
    except:
        break

            
    

发表于 2021-02-01 23:01:25 回复(0)
为什么下面代码在牛客网oj没有输出?
import sys


class Solution:
    def __init__(self):
        self.num_to_chinese = {
            1: "壹", 2: "贰", 3: "叁", 4: "肆", 5: "伍", 6: "陆", 7: "柒", 8: "捌", 9: "玖",
            10: "拾", 100: "佰", 1000: "仟", 10000: "万", 100000000: "亿",
            # 0.1: "角", 0.01: "分"
        }
        self.chinese = "人民币"

    def int_money_to_chinese(self, int_money):
        if 10 > int_money > 0:
            return self.num_to_chinese[int_money]
        chinese = ""
        order = [100000000, 10000, 1000, 100, 10]
        for i in order:
            tmp = int_money // i
            if tmp == 0:
                if len(self.chinese) > 3 and self.chinese[-1] != "零":
                    self.chinese += "零"
                continue
            chinese += self.int_money_to_chinese(tmp)
            chinese += self.num_to_chinese[i]
            int_money = int_money % i
        return chinese

    def money_to_chinese(self, money):
        self.chinese += self.int_money_to_chinese(int(money))
        if len(self.chinese) > 3:
            self.chinese += "元"

        part2 = ""
        if int(money * 10) % 10 != 0:
            part2 += self.num_to_chinese[int(money * 10) % 10] + "角"
        if int(money * 100) % 10 != 0:
            part2 += self.num_to_chinese[int(money * 100) % 10] + "分"
        if len(part2) == 0:
            part2 = "整"
        self.chinese += part2

        return self.chinese


if __name__ == '__main__':
    money = float(sys.stdin.readline().strip())
    solution = Solution()
    print(solution.money_to_chinese(money))


发表于 2020-08-12 14:38:52 回复(1)
赚点人民币,真tmd费劲



import java.util.*;

public class Main {
    public static void main(String[] args) {
        Map<Integer, String> map = new HashMap<>();
        initMap(map);
        Scanner scanner = new Scanner(System.in);
        while(scanner.hasNextLine()) {
            String money = scanner.nextLine();
            String[] arr = money.split("\\.");
            String res = "";
            // 整数部分
            int size = arr[0].length() % 4 == 0 ? arr[0].length()/4 : arr[0].length()/4+1;
            String[] strs = new String[size];
            int index = 0;
            String tmp = "";
            for (int i=arr[0].length()-1;i>=0;i--) {
                tmp= tmp + arr[0].charAt(i);
                if(tmp.length() == 4) {
                    strs[index] = tmp;
                    tmp="";
                    index++;
                } else {
                    if (i==0) {
                        strs[strs.length-1]=tmp;
                    }
                }
            }
            for(int i=0;i<strs.length;i++){
                String s = strs[i];
                String resTmp = "";
                for(int j=0;j<s.length();j++){
                    int a = s.charAt(j) - 48;
                    String b = map.get(a);
                    if (a!=0) {
                        switch (j){
                            case 1:
                                b =b  + "拾";
                                break;
                            case 2:
                                b=b + "佰";
                                break;
                            case 3:
                                b =b + "仟";
                                break;
                            default:
                                break;
                        }
                    }
                    resTmp = b + resTmp;
                }
                switch(i) {
                    case 0:
                        resTmp = resTmp + "元";
                        break;
                    case 1:
                        resTmp = resTmp + "万";
                        break;
                    case 2:
                        resTmp = resTmp + "亿";
                        break;
                    default:
                        break;
                }
                res = resTmp + res;
            }
            // 小数部分
            if ("00".equals(arr[1])) {
                res = res + "整";
            } else {
                for (int i=0;i<arr[1].length();i++) {
                    int x = arr[1].charAt(i) - 48;
                    if (x != 0) {
                        res = res + map.get(x);
                        if (i==0) {
                            res = res + "角";
                        } else if (i==1) {
                            res = res + "分";
                        }
                    }
                }
            }
            res = res.replaceAll("零+", "零");
            res = res.replaceAll("零元", "元");
            res = res.replaceAll("壹拾", "拾");
            if (res.charAt(0) == '元') {
                res= res.substring(1);
            }
            System.out.println("人民币"+ res);
        }
    }
    public static void initMap(Map<Integer, String> map) {
        map.put(0, "零");
        map.put(1, "壹");
        map.put(2, "贰");
        map.put(3, "叁");
        map.put(4, "肆");
        map.put(5, "伍");
        map.put(6, "陆");
        map.put(7, "柒");
        map.put(8, "捌");
        map.put(9, "玖");
    }
}


发表于 2020-07-18 16:18:13 回复(0)
这个长度还可以吧,大哥们可以给个赞赞吗
#include<iostream>
using namespace std;
int main()
{
    string str;
    string a[]={"零","壹","贰","叁","肆","伍","陆","柒","捌","玖","拾"};
    string b[]={"","拾","佰","仟"};
    string c[]={"","万","亿"};
    while(cin>>str){
        string result="";
        int x=str.find('.');
        int flag=0;
        for(int index=x-1,i=0;index>=0;index--,i++){
            if(i%4==0){
                result = c[i/4]+result;
            }
            if(str[index]=='0'){
                if(i!=0 && str[index+1]!='0'){
                    result = a[0]+result;
                }
            }
            else{
                flag = 1;
                result = b[i%4]+result;
                if(!(i%4==1&&str[index]=='1')) result = a[str[index]-'0'] + result;
            }
            if(index==0&&flag){
                result = result + "元";
            }
        }
        if(str[x+1]=='0'&&str[x+2]=='0'){
            result = result+"整";
        }
        else{
            if(str[x+1]!='0') result = result + a[str[x+1]-'0'] + "角";
            if(str[x+2]!='0') result = result + a[str[x+2]-'0'] + "分";
        }
        result = "人民币" + result;
        cout<<result<<endl;
    }
    return 0;
}


发表于 2020-07-17 18:50:00 回复(0)
递归解法,最后len = 2 和 len = 1的部分写的不是很好,可以改的更清晰一点
def RMB(zhengshu):
    #处理zhengshu开头多个0的情况
    if zhengshu.count('0') == len(zhengshu):
        return ''
    if zhengshu[0] == '0':
        for i in range(len(zhengshu)-1):
            if zhengshu[i+1] != '0':
                zhengshu = zhengshu[i:]
                break
            else:
                continue
    #字典
    chinese_dict = {'1':'壹','2':'贰','3':'叁','4':'肆','5':'伍','6':'陆','7':'柒','8':'捌','9':'玖','0':'零'}
    res = ''
    #开始recursion
    if len(zhengshu) >= 9:
        res = RMB(zhengshu[:len(zhengshu)-8]) + '亿' + RMB(zhengshu[len(zhengshu)-8:])
    elif len(zhengshu) >= 5:
        res = RMB(zhengshu[:len(zhengshu)-4]) + '万'+RMB(zhengshu[len(zhengshu)-4:])
    elif len(zhengshu) == 4:
        if zhengshu[0] == '0':
            res = chinese_dict[zhengshu[0]] + RMB(zhengshu[1:])
        else:
            res = chinese_dict[zhengshu[0]] + '仟' + RMB(zhengshu[1:])
    elif len(zhengshu) == 3:
        if zhengshu[0] == '0':
            res = chinese_dict[zhengshu[0]] + RMB(zhengshu[1:])
        else:
            res = chinese_dict[zhengshu[0]] + '佰' + RMB(zhengshu[1:])
    elif len(zhengshu) == 2:
        if zhengshu[0] == '0' and zhengshu[1] != '0':
            res = chinese_dict[zhengshu[0]] + chinese_dict[zhengshu[1]]
        if zhengshu[0] != '0' and zhengshu[1] == '0':
            if zhengshu[0] == '1':
                res = '拾'
            else:
                res = chinese_dict[zhengshu[0]] + '拾'
        if zhengshu[0] != '0' and zhengshu[1] != '0':
            if zhengshu[0] == '1':
                res = '拾' + chinese_dict[zhengshu[1]]
            else:
                res = chinese_dict[zhengshu[0]] + '拾' + chinese_dict[zhengshu[1]]
        if zhengshu[0] == '0' and zhengshu[1] == '0':
            res = ''
    elif len(zhengshu) == 1:
        if zhengshu[0] != '0':
            res = chinese_dict[zhengshu[0]]
    return res
def xiaoshu(m):
    res = ''
    chinese_dict = {'1':'壹','2':'贰','3':'叁','4':'肆','5':'伍','6':'陆','7':'柒','8':'捌','9':'玖','0':'零'}
    if m[0] == '0' and m[1] != '0':
        res = chinese_dict[m[1]] + '分'
    if m[0] != '0' and m[1] == '0':
        res = chinese_dict[m[0]] + '角'
    if m[0] != '0' and m[1] != '0':
        res = chinese_dict[m[0]] + '角' + chinese_dict[m[1]] + '分'
    if m[0] == '0' and m[1] == '0':
        res = '整'
    return res
def driver(s):
    zhengshu = s.split('.')[0]
    m = s.split('.')[1]
    zhengshu_res = RMB(zhengshu)
    xiaoshu_res = xiaoshu(m)
    if len(zhengshu_res) != 0:
        res = '人民币' + RMB(zhengshu) + '元' + xiaoshu(m)
    else:
        res = '人民币' + RMB(zhengshu) + xiaoshu(m)
    return res
while True:
    try:
        s = input()
        print(driver(s))
    except:
        break

            
    


发表于 2020-07-02 17:04:04 回复(1)
/*我做了好几个小时,快8个小时了,真实笔试早就挂了......*/
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

const int Y = 100000000;
string look[10] = { "零","壹","贰","叁","肆","伍","陆","柒","捌","玖" }; /*数字映射成汉字*/

void Modify(int cur, int prev, string Flag, string &Ret) { /*参数说明: 当前值, 当前值的前置值, 单位, 结果*/
    if (cur != 0) {
        Ret = Ret + look[cur] + Flag;
    }
    else {
        if (prev != 0) { /*对零的处理,只处理第一个零,后面的零则不处理*/
            Ret = Ret + look[0];
        }
    }
}

string Dealcommon(int a2, int prev) { /*一些重复的代码,单独抽象出来,a2是万以内的数,prev是前置值*/
    string s1 = "";
    int b1 = a2 / 1000;
    Modify(b1, prev, "仟", s1);
    int b2 = (a2 - b1 * 1000) / 100;
    Modify(b2, b1, "佰", s1);
    int b3 = (a2 - b1 * 1000 - b2 * 100) / 10;
    Modify(b3, b2, "拾", s1);
    int b4 = a2 % 10;
    Modify(b4, b3, "", s1);
    return s1;
}

string DealLeft(int n) {
    if (n == 0) {
        return "";
    }
    else { /*分成三段*/
        int a1 = n / Y;
        string s1 = DealLeft(a1); //超过一亿的问题是子问题, 不过最多只能处理INT_MAX.
        if (s1 != "") {
            s1 = s1 + "亿";
        }
      /*处理千万到万的部分*/
        int a2 = (n - a1 * Y) / 10000;
        string temp2 = Dealcommon(a2, a1 % 10);
        s1 = s1 + temp2;
        if (a2 > 0) {
            s1 = s1 + "万";
        }
/*处理万以下的部分*/
        int a3 = n % 10000;
        string temp3 = Dealcommon(a3, a2 % 10);
        s1 = s1 + temp3;
        return s1;
    }
}

string DealRight(int left, int right) { /*小数部分的处理*/
    string temp = "";
    int a1 = right / 10;
    if (a1 != 0) {
        Modify(a1, (left % 10), "角", temp);
    }
    int a2 = right % 10;
    if (a2 != 0) { /*小数部分的0不用处理*/
        Modify(a2, a1, "分", temp);
    }
    if (left != 0) {
        if (temp == "") {
            return "元整";
        }
        else {
            return string("元") + temp;
        }
    }
    else {
        return temp;
    }
}

string GetStr(string s)  {  /*使用string来传参数是为了精度问题,不能用double*/
    size_t n = s.find('.');
    string k = s.substr(0, n);
    int left = atoi(k.c_str());  /*提取小数点左边的int*/
    k = s.substr(n + 1);
    int right = atoi(k.c_str()); /*提取小数点右边的int*/
    string l = DealLeft(left);
    string::size_type tpos = l.find("壹拾"); /*处理壹拾开头的数*/
    if (tpos != string::npos) {
        if (tpos == 0) { 
            tpos = l.find("拾"); /*,这里涉及到中文字符的编码问题,偷个懒*/
            l = l.substr(tpos);
        }
    }

    string r = DealRight(left, right);
    string Ret = string("人民币") + l + r; /*将左边结果与右边结果合并*/
    string::size_type t = Ret.rfind(look[0]); /*去掉以零结尾的情况,具体参考对零的处理*/
    if (t != string::npos) {
        string temp = Ret.substr(t);
        if (temp == look[0]) {
            Ret = Ret.substr(0, t);
        }
    }
    return Ret;
}

int main() {
    string s;
    while (cin >> s) {
        cout << GetStr(s) << endl;
    }
    system("pause");
    return 0;
}


编辑于 2020-06-18 13:05:23 回复(0)
有一题是数字转英文,和本题类似,但本题难度要比那个大点。
#include <stdio.h>

const char temp1[10][10] = {"零","壹","贰","叁","肆","伍","陆","柒","捌","玖"};
const char temp2[10][10] = {"拾","拾壹","拾贰","拾叁","拾肆","拾伍","拾陆","拾柒","拾捌","拾玖"};
const char temp3[10][10] = {"零","壹拾","贰拾","叁拾","肆拾","伍拾","陆拾","柒拾","捌拾","玖拾"};

void print(int money)
{
    if(money < 10)
    	printf("%s",temp1[money]);
   	if(money>=10 && money <20)
   		printf("%s",temp2[money-10]);
    if(money>=20 && money <100)
    {
    	if(money%10 == 0) 
    		printf("%s",temp3[money/10]);
    	else
    		printf("%s%s",temp3[money/10],temp1[money%10]);
	}	
   	if(money>=100 && money <1000)
    {
    	if(money%100/10 == 0)
    		{printf("%s佰零%s",temp1[money/100],temp1[money%10]);}
		else
			{printf("%s佰",temp1[money/100]);print(money%100);}	
    }
    if(money>=1000 && money <10000)
    {
    	if(money%1000/100 == 0)
    		{printf("%s仟零",temp1[money/1000]);print(money%1000);}
		else
			{printf("%s仟",temp1[money/1000]);print(money%1000);}	
    }
    if(money>=10000 && money <100000000)
    {
    	print(money/10000);
    	if(money%10000/1000==0)
    		printf("万零");
   		else
   	 		printf("万");
    	print(money%10000);	
    }
}

int main()
{
    double money,small;
    int small_int;
    while(scanf("%lf",&money)!= EOF)
    {
    	printf("人民币");
    	if(money < 1 && money > 1e-6)        //判断是否为为0.x元
		{
			small_int = (money+0.005)*100;
			if(small_int/10 ==0)
				printf("%s分\n",temp1[small_int%10]);
			else if(small_int%10 ==0)
				printf("%s角\n",temp1[small_int/10]);
			else
				printf("%s角%s分\n",temp1[small_int/10],temp1[small_int%10]);
			continue;
		}
        print((int)money);
        small = (money -(int)money) + 0.005;
		if( small < 0.01)                //判断是否为整
			printf("元整\n");
		else                            //为xxx.xx
		{
			small_int = small*100;
			if(small_int/10 ==0)
				printf("元%s分\n",temp1[small_int%10]);
			else if(small_int%10 ==0)
				printf("元%s角\n",temp1[small_int/10]);
			else
				printf("元%s角%s分\n",temp1[small_int/10],temp1[small_int%10]);
		}
    }
    return 0;
}


发表于 2020-04-14 14:27:55 回复(0)
/*
水木清华
2020-03-18
人民币转换
基于 ultraji 朋友的代码
输出模式:个位与其他单位的组合 + 元 + 个位 + 角 + 个位 + 分,或,个位与其他单位的组合 + 元整。
*/
#include <iostream>
using namespace std;
//构建个位的字典(数组)
string gewei[10] = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
//构建十位、百位、千位、万位、亿位等其他单位的字典(数组),ot[10] 实际表示 "拾亿",ot[15] 实际表示 "佰万亿"
string other[17] = {"", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰", "仟", "万", "拾", "佰", "仟","万"};
//获取元钱的函数接口,即小数点之前的部分
void Get_Before_Plot(string str)
{
    if (str == "0")
    {
        return;
    }
    int j = str.size() - 1;
    if(!(j % 4 == 1 && str[0] == '1'))
    {
        cout << gewei[str[0]-'0'];
    }
    cout << other[j];
    for(int i = 1; i < str.size(); i++)
    {
        if( (j - i) % 4 == 0  && str[i] == '0')
        {
            if (i >= 4 && j - i == 4 && str[i - 1] + str[i - 2] + str[i - 3] == '0' * 3)
            {
                continue;
                cout << other[j - i];
            }
            continue;
        }
        if(str[i] != '0')
        {
            if(str[i - 1] == '0')
            {
                cout << "零";
            }
            cout << gewei[str[i] - '0'];
            cout << other[j - i];
        }
    }
    cout << "元";
    return;
}
//获取角分零钱的函数接口,即小数点之后的部分
void Get_After_Plot(string str)
{
    if(str == "00")
    {
        cout << "整";
        return ;
    }
    if (str[0] > '0')
    {
        cout << gewei[str[0]-'0'] << "角";
    }
    if (str[1] > '0')
    {
        cout << gewei[str[1]-'0'] << "分";
    }
    return;
}
//主函数 
int main()
{
    string str;
    while(getline(cin, str))
    {
        //获取小数点的位置
        int Plot = str.find('.');
        //获取小数点前的子字符串
        string str1 = str.substr(0, Plot);
        //获取小数点后的子字符串
        string str2 = str.substr(Plot + 1);
        //输出人民币
        cout << "人民币";
        //输出元钱
        Get_Before_Plot(str1);
        //输出角分零钱
        Get_After_Plot(str2);
        //换行
        cout << endl;
    }
    return 0;
}

发表于 2020-03-18 13:16:02 回复(0)
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		while(sc.hasNext()) {
			String money = sc.next();
			String[] str = money.split("\\.");
			
			StringBuilder sb = new StringBuilder();
			while(str[0].length()%4!=0) {
				str[0]="0"+str[0];
			}
			for(int i=str[0].length()/4-1,j=0;i>=0;i--,j+=4) {
				sb.append(toStr(str[0].substring(j,j+4),i));
			}
			
			if(sb.toString().equals("元")) {
				sb=new StringBuilder();
			}
			
			if(str[1].length()==0||str[1].equals("0")||str[1].equals("00")) {
				if(sb.length()!=0) {
					sb.append("整");
				}
			}else {
				while(str[1].length()%4!=0) {
					str[1]="0"+str[1];
				}
				str[1]=toStr(str[1],3).replace("拾", "角");
				while(str[1].startsWith("零")) {
					str[1]=str[1].substring(1);
				}
				if(!str[1].endsWith("角")) {
					str[1]=str[1]+"分";
				}
				sb.append(str[1]);
			}
			
			
			money = sb.toString();
			if(money.startsWith("零")) {
				money=money.substring(1);
			}	
            money = money.replace("壹拾", "拾");
			
			System.out.println("人民币"+money);			
		}	
	}
	
	public static String toStr(String val,int flag) {
		StringBuilder sb  = new StringBuilder();
		for(int i=0;i<val.length();i++) {
			switch(val.charAt(i)) {
			case '0':sb.append("零");break;
			case '1':sb.append("壹");break;
			case '2':sb.append("贰");break;
			case '3':sb.append("叁");break;
			case '4':sb.append("肆");break;
			case '5':sb.append("伍");break;
			case '6':sb.append("陆");break;
			case '7':sb.append("柒");break;
			case '8':sb.append("捌");break;
			case '9':sb.append("玖");break;
			}
			switch(i){
				case 0:sb.append("仟");break;
				case 1:sb.append("佰");break;
				case 2:sb.append("拾");break;
			}
		}	
		String str = sb.toString();	
		str = str.replaceAll("(零.)+", "零");
		while(str.endsWith("零")) {
			str=str.substring(0, str.length()-1);
		}
		
		switch(flag) {
		case 0:str=str+"元";break;
		case 1:str=str+"万";break;
		case 2:str=str+"亿";break;
		case 3:break;
		}	
		return str;
	}
}

发表于 2020-02-19 01:07:13 回复(0)
1.将0~9保存为数组;
2.对不同占位的数字进行单位换算(元、拾、佰、仟、万、亿),是有一定规律的;
3.除了打印固定字符外,分别打印整数部分和小数部分;
4.对整数部分,逢拾且数字为1的位置不做数字输出。
#include <iostream>

using namespace std;

string Number[] = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
string Unit[] = {"", "元", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰", "仟", "亿"};

void printInter(int inter)
{
    int count = 0;
    int money = inter;
    while(money%10)
    {
        count++;
        money /= 10;
    }
    money = inter;
    for(int i = count; i > 0; i--)
    {
        int ten = 1;
        for(int j = i - 1; j > 0; j--)
            ten *= 10;
        //cout<< money/ten << ", " << i << endl;
        if(((2 != i) || (1 != money/ten)) &&
           ((6 != i) || (1 != money/ten)) &&
           ((10 != i) || (1 != money/ten)))
            cout << Number[money/ten];
        cout << Unit[i];
        money = money%ten;
    }
}

void printDot(double doter)
{
    int dot = (int)(doter*100 + 0.5f);
    if(0 == dot)
    {
        cout << "整";
    }
    else
    {
        //cout << dot << endl;
        if(0 != dot/10)
        {
            cout << Number[dot/10];
            cout << "角";
        }
        if(0 != dot%10)
        {
            cout << Number[dot%10];
            cout << "分";
        }
    }
}

int main(int argc, char *argv[])
{
    double money;
    while(cin >> money)
    {
        int inter = (int)money;
        double doter = money - inter;
        cout << "人民币";
        printInter(inter);
        printDot(doter);
        cout << endl;
    }
    return 0;
}



发表于 2019-10-22 17:59:09 回复(2)
package mianshi;
import java.util.Scanner;
public class Main2 {
    static String output="人民币";
    static String[] money;
    public static void main(String[] args){

        Scanner sc = new Scanner(System.in);//输入 
        while (sc.hasNextLine()) {
            String sentence=sc.nextLine();
            money=sentence.split("\\.");
            if(sentence.contains(".")){
                leftRead(money[0]);
                output+="元";
                rightRead(money[1]);
            }else{
                leftRead(money[0]);
                output+="元整";
            }

            if(output.contains("零元") && !output.equals("人民币零元整")){
                output= output.substring(0,3)+output.substring(5,output.length());
            }
            System.out.println(output);
            output="人民币";
        }
    }

    public static void rightRead(String money){
        char[] right=money.toCharArray();
        if(right[0]=='0' && right[1]=='0'){
            output+="整";
            return;
        }
        for(int i = 0 ; i<2;i++){
            if(!(i==1 && right[1]=='0')){// 1.40 时不打出0分
                output += number(Integer.parseInt(String.valueOf(right[i])));
                if(!output.endsWith("零")){
                    output += right(i);
                }else{
                    output=output.substring(0,output.length()-1);//去掉最后的文字
                }
            }
        }

    }
    public static void leftRead(String money){
        char[] left=money.toCharArray();
        int length = money.length();

        for(int i=left.length-1;i>=0;i--){
            if(output.endsWith("零")&&Integer.parseInt((String.valueOf(left[(left.length-1)-i])))==0){//连续多个零的情况
              if(Integer.parseInt((String.valueOf(left[(left.length-1)-i])))!=0 || i%4==0){ // i%4==0  打出万亿兆等单位
                 if( (left(i+1)=="万"||left(i+1)=="亿" ) &&output.endsWith("零")){
                     output=output.substring(0,output.length()-1);//去掉最后的文字
                 }
                output += left(i+1);
              }
              continue;
            }
            if(!((left.length%4==2 )&& i==left.length-1 && Integer.parseInt((String.valueOf(left[(left.length-1)-i])))==1)){// 10输出十   100输出一百  
                output += number(Integer.parseInt((String.valueOf(left[(left.length-1)-i]))));
            }
            if(Integer.parseInt((String.valueOf(left[(left.length-1)-i])))!=0 || i%4==0){ // i%4==0  打出万亿兆等单位
                output += left(i+1);
            }
        }
    }
    public static String right(int i){
        switch(i){
        case 0: 
            return "角";
        case 1:
            return "分";
        }
        return "";
    }
    public static String left(int i){
        if(i==0){
            return "";
        }
        int k= i%13;
        switch(k){
        case 0: 
            return "兆";
        case 1:
            return "";
        case 2:
            return "拾";
        case 3:
            return "佰";
        case 4:
            return "仟";
        case 5:
            return "万";
        case 6:
            return "拾";
        case 7:
            return "佰";
        case 8:
            return "仟";
        case 9:
            return "亿";
        case 10:
            return "拾";
        case 11:
            return "佰";
        case 12:
            return "仟";

        }
        return "";
    }
    public static String number(int i){
        switch(i){
        case 0: 
            return "零";
        case 1:
            return "壹";
        case 2:
            return "贰";
        case 3:
            return "叁";
        case 4:
            return "肆";
        case 5:
            return "伍";
        case 6:
            return "陆";
        case 7:
            return "柒";
        case 8:
            return "捌";
        case 9:
            return "玖";
        }
        return "";
    }

}
编辑于 2019-07-30 11:38:20 回复(0)
import java.util.*;
public class Main{
    public static String change(long b){
        if(b==1)
            return "壹";
        if(b==2)
            return"贰";
        if(b==3)
            return"叁";
        if(b==4)
            return"肆";
        if(b==5)
            return"伍";
        if(b==6)
            return"陆";
        if(b==7)
            return"柒";
        if(b==8)
            return"捌";
        if(b==9)
            return"玖";
        return  null;
    }
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        while(in.hasNext()){
            double a = in.nextDouble();
            int b = (int)a%10000;//元
            int c = (int)a/10000%10000;//万
            int d =  (int)a/100000000%10000;//亿
            int count = 0;
            StringBuilder str = new StringBuilder();
            System.out.print("人民币");
            if(d>0){
                int qian = d/1000;
                int bai = d%1000/100;
                int shi = d%100/10;
                int ge = d%10;
                if(qian>0){
                    str.append(change(qian)+"仟");
                }else {
                    if (!str.toString().isEmpty()&&str.toString().charAt(str.length()-1)!='零'){
                        str.append("零");
                    }
                }
                if(bai>0){
                    str.append(change(bai)+"佰");
                }else {
                    if (!str.toString().isEmpty()&&str.toString().charAt(str.length()-1)!='零'){
                        str.append("零");
                    }
                }
                if(shi>0){
                    if(shi==1&&qian==0&&bai==0){
                        str.append("拾");
                    }else{
                        str.append(change(shi)+"拾");
                    }
                }else {
                    if (!str.toString().isEmpty()&&str.toString().charAt(str.length()-1)!='零'){
                        str.append("零");
                    }
                }
                if(ge>0){
                    str.append(change(ge));
                }
                str.append("亿");
            }
            if(c>0){
                int qian = c/1000;
                int bai = c%1000/100;
                int shi = c%100/10;
                int ge = c%10;
                if(qian>0){
                    str.append(change(qian)+"仟");
                }else {
                    if (!str.toString().isEmpty()&&str.toString().charAt(str.length()-1)!='零'){
                        str.append("零");
                    }
                }
                if(bai>0){
                    str.append(change(bai)+"佰");
                }else {
                    if (!str.toString().isEmpty()&&str.toString().charAt(str.length()-1)!='零'){
                        str.append("零");
                    }
                }
                if(shi>0){
                    if(shi==1&&qian==0&&bai==0){
                        str.append("拾");
                    }else{
                        str.append(change(shi)+"拾");
                    }
                }else {
                    if (!str.toString().isEmpty()&&str.toString().charAt(str.length()-1)!='零'){
                        str.append("零");
                    }
                }
                if(ge>0){
                    str.append(change(ge));
                }
                str.append("万");
            }
            if(b>0){
                int qian = b/1000;
                int bai = b%1000/100;
                int shi = b%100/10;
                int ge = b%10;
                if(qian>0){
                    str.append(change(qian)+"仟");
                }else {
                    if (!str.toString().isEmpty()&&str.toString().charAt(str.length()-1)!='零'){
                        str.append("零");
                    }
                }
                if(bai>0){
                    str.append(change(bai)+"佰");
                }else {
                    if (!str.toString().isEmpty()&&str.toString().charAt(str.length()-1)!='零'){
                        str.append("零");
                    }
                }
                if(shi>0){
                    if(shi==1&&qian==0&&bai==0){
                        str.append("拾");
                    }else{
                        str.append(change(shi)+"拾");
                    }
                }else {
                    if (!str.toString().isEmpty()&&str.toString().charAt(str.length()-1)!='零'){
                        str.append("零");
                    }
                }
                if(ge>0){
                    str.append(change(ge));
                }
                str.append("元");
            }
            double x = a*1000/10;
            long t = (int)(a*1000/10);
            long m = (int)a;
            long xiao = t - m*100;
            if (xiao==0){
                str.append("整");
            }
            if(xiao>0){
                long jiao = xiao/10;
                long fen = xiao%10;
                if(jiao>0){
                    str.append(change(jiao)+"角");
                }
                if(fen>0){
                    str.append(change(fen)+"分");
                }
            }
            System.out.println(str.toString());
        }
    }
}

编辑于 2019-07-29 14:21:53 回复(1)
import java.util.*;

//考虑到所有的情况,应该是最佳答案了

//壹、贰、叁、肆、伍、陆、柒、捌、玖、拾、佰、仟、万、亿、元、角、分、零、整
public class Main{
    public static void main(String []args){
        Scanner in=new Scanner(System.in);
        while(in.hasNext()){
        String str=in.nextLine();
        String []sts=str.split("\\.");
        String s=sts[0];
        StringBuilder sb=new StringBuilder("人民币");
        for (int j=0,i=s.length()-1;i>=0;i--,j++){
            if (s.charAt(j)!='0') {
                if (j>=3 && i%4==0 &&s.charAt(j-1)=='0'&&s.charAt(j-2)=='0'){
                    sb.append("零");
                }
                if (s.charAt(j)=='1' && i%4-1==0) {
                }else {
                    sb.append(Num(s.charAt(j)));
                }
            }
            if (i!=0) {
                if (i % 8 == 0 && i >= 8) {
                    sb.append("亿");
                }
                if (i % 4 == 0 && i % 8 != 0) {
                    sb.append("万");
                }
                if (i % 4-3 == 0 && s.charAt(j)!='0') {
                    sb.append("仟");
                    if (s.charAt(j+1)=='0'&&s.charAt(j+2)!='0'){
                        sb.append("零");
                    }
                }
                if (i % 4-2 == 0 && s.charAt(j)!='0') {
                    sb.append("佰");
                    if (s.charAt(j+1)=='0'&& s.charAt(j+2)!='0'){
                        sb.append("零");
                    }
                }
                if (i % 4-1 == 0&& s.charAt(j)!='0') {
                    sb.append("拾");
                }
            }
        }
        if (s.charAt(0)!='0'){
            sb.append("元");
        }
        if (sts[1].equals("00")){
            sb.append("整");
        }else{
            if (sts[1].charAt(0)=='0'){
                sb.append(Num(sts[1].charAt(1)));
                sb.append("分");
            }
            if (sts[1].charAt(1)=='0'){
                sb.append(Num(sts[1].charAt(0)));
                sb.append("角");
            }
            if (sts[1].charAt(0)!='0'&&sts[1].charAt(1)!='0'){
                sb.append(Num(sts[1].charAt(0)));
                sb.append("角");
                sb.append(Num(sts[1].charAt(1)));
                sb.append("分");
            }
        }
        System.out.println(sb);
        }
    }
    public static String Num(char c){
        if (c=='1'){
            return "壹";
        }if (c=='2'){
            return "贰";
        }if (c=='3'){
            return "叁";
        }if (c=='4'){
            return "肆";
        }if (c=='5'){
            return "伍";
        }if (c=='6'){
            return "陆";
        }if (c=='7'){
            return "柒";
        }if (c=='8'){
            return "捌";
        }if (c=='9'){
            return "玖";
        }
        return null;
    }
}

发表于 2019-07-29 10:17:08 回复(0)
import java.util.*;
public class Main{
public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            String result = "人民币";
            String string = sc.nextLine();
            String[] arrs = string.split("\\.");
            // 小数点前
            // 看是否有亿级
            if (arrs[0].length() <= 4)// XXXX级别
                result = result + toCNsentence(arrs[0]);
            else if (arrs[0].length() > 4 && arrs[0].length() <= 8) {// XXXX,XXXX级别
                String str1 = arrs[0].substring(0, arrs[0].length() - 4);
                String str2 = arrs[0].substring(arrs[0].length() - 4);
                result = result + toCNsentence(str1) + "万" + toCNsentence(str2);
            } else {// XXXX,XXXX,XXXX级别
                String str1 = arrs[0].substring(0, arrs[0].length() - 8);
                String str2 = arrs[0].substring(arrs[0].length() - 8, arrs[0].length() - 4);
                String str3 = arrs[0].substring(arrs[0].length() - 4);
                result = result + toCNsentence(str1) + "亿" + toCNsentence(str2) + "万" + toCNsentence(str3);
            }
            // 整数分析完后价格个元
            if(result.charAt(result.length()-1)!='币')
            result = result + "元";
            // 小数点后
            if (arrs[1].charAt(0) == '0' && arrs[1].charAt(1) == '0')
                result = result + "整";
            else if (arrs[1].charAt(0) == '0' && arrs[1].charAt(1) != '0')
                result = result + toCNword(arrs[1].charAt(1)) + "分";
            else if (arrs[1].charAt(0) != '0' && arrs[1].charAt(1) == '0') {
                result = result + toCNword(arrs[1].charAt(0)) + "角";
            } else {
                result = result + toCNword(arrs[1].charAt(0)) + "角" + toCNword(arrs[1].charAt(1)) + "分";
            }
            System.out.println(result);
        }
    }

    private static String toCNsentence(String str) {
        String result = "";
        if (str.length() == 1) {
            if(str.charAt(0)!='0')result = toCNword(str.charAt(0));
        }
        if (str.length() == 2)// 30 25 10 15几种情况
        {
            if (str.charAt(0) == '1')
                result = result + "拾";
            else
                result = result + toCNword(str.charAt(0)) + "拾";
            if (str.charAt(1) != '0')
                result = result + toCNword(str.charAt(1));
        }
        if (str.length() == 3)// 300 301 315
        {
            result = result + toCNword(str.charAt(0)) + "佰";
            if (str.charAt(1) == '0')
                result = result + "零" + toCNword(str.charAt(2));
            else
                result = result + toCNword(str.charAt(1)) + "拾" + toCNword(str.charAt(2));
        }
        if (str.length() == 4 && str.charAt(0) != '0')// 4310 4001 4021 4102                                                // 4300
        {
            result = result + toCNword(str.charAt(0)) + "仟";
            if (str.charAt(1) == '0' && str.charAt(2) == '0' && str.charAt(3) == '0') {
                // 如果都是0 则直接是 X000
            } else if (str.charAt(1) == '0' && str.charAt(2) == '0' && str.charAt(3) != '0') {
                result = result + "零" + toCNword(str.charAt(3));// X00X
            } else if (str.charAt(1) != '0' && str.charAt(2) == '0' && str.charAt(3) == '0') {
                result = result + toCNword(str.charAt(1)) + "佰";// XX00
            } else if (str.charAt(1) == '0' && str.charAt(2) != '0' && str.charAt(3) == '0') {
                result = result + "零" + toCNword(str.charAt(2)) + "拾";// X0X0
            } else if (str.charAt(1) != '0' && str.charAt(2) != '0' && str.charAt(3) == '0') {
                result = result + toCNword(str.charAt(1)) + "佰" + toCNword(str.charAt(2)) + "拾";// XXX0
            } else if (str.charAt(1) != '0' && str.charAt(2) == '0' && str.charAt(3) != '0') {
                result = result + toCNword(str.charAt(1)) + "佰" + "零" + toCNword(str.charAt(3));// XX0X
            } else if (str.charAt(1) != '0' && str.charAt(2) == '0' && str.charAt(3) != '0') {
                result = result + toCNword(str.charAt(1)) + "佰" + toCNword(str.charAt(2)) + "拾";// XXX0
            } else {
                result = result + toCNword(str.charAt(1)) + "佰" + toCNword(str.charAt(2)) + "拾"
                        + toCNword(str.charAt(3));// XXXX
            }
        } else if (str.length() == 4&&str.charAt(0) == '0') {
            if (str.charAt(1) == '0' && str.charAt(2) == '0' && str.charAt(3) == '0') {
                result = result + "零";// 如果都是0 则直接是 0000
            } else if (str.charAt(1) == '0' && str.charAt(2) == '0' && str.charAt(3) != '0') {
                result = result + "零" + toCNword(str.charAt(3));// 000X
            } else if (str.charAt(1) != '0' && str.charAt(2) == '0' && str.charAt(3) == '0') {
                result = result + toCNword(str.charAt(1)) + "佰";// 0X00
            } else if (str.charAt(1) == '0' && str.charAt(2) != '0' && str.charAt(3) == '0') {
                result = result + "零" + toCNword(str.charAt(2)) + "拾";// 00X0
            } else if (str.charAt(1) != '0' && str.charAt(2) != '0' && str.charAt(3) == '0') {
                result = result + "零" + toCNword(str.charAt(1)) + "佰" + toCNword(str.charAt(2)) + "拾";// 0XX0
            } else if (str.charAt(1) != '0' && str.charAt(2) == '0' && str.charAt(3) != '0') {
                result = result + "零" + toCNword(str.charAt(1)) + "佰" + "零" + toCNword(str.charAt(3));// 0X0X
            } else if (str.charAt(1) != '0' && str.charAt(2) == '0' && str.charAt(3) != '0') {
                result = result + "零" + toCNword(str.charAt(1)) + "佰" + toCNword(str.charAt(2)) + "拾";// 0XX0
            } else {
                result = result + "零" + toCNword(str.charAt(1)) + "佰" + toCNword(str.charAt(2)) + "拾"
                        + toCNword(str.charAt(3));// 0XXX
            }
        }
        return result;
    }

    private static String toCNword(char charAt) {
        String result = "";
        if (charAt == '1')
            result = "壹";
        else if (charAt == '2')
            result = "贰";
        else if (charAt == '3')
            result = "叁";
        else if (charAt == '4')
            result = "肆";
        else if (charAt == '5')
            result = "伍";
        else if (charAt == '6')
            result = "陆";
        else if (charAt == '7')
            result = "柒";
        else if (charAt == '8')
            result = "捌";
        else if (charAt == '9')
            result = "玖";
        else if (charAt == '0')
            result = "零";
        return result;
    }

}

完美通过
两个要注意的地方其他的好像就没了
别人问就是列举出来
1.07   人民币一元七分
0.85   人民币八角五分
发表于 2019-07-03 20:40:32 回复(1)
思路是把数字每4位分一组,分别输出 代码较简单   #include<iostream>
#include<string>
#include<cmath>
#include<vector>
using namespace std;
const string h1[10]={"零","壹","贰","叁","肆","伍","陆","柒","捌","玖"};
const string h2[4]={"","拾","佰","仟"};
const string h3[6]={"元","万","亿","角","分","整"};
int main(){
    double num;
    while(cin>>num){
        long long itg = (long long)num;//整数部分
        int deci= round((num - itg)*100);//小数部分
        vector<int> v;
        while (itg) {//每4位一组
            v.push_back(itg % 10000);
            itg /= 10000;
        }
        cout<<"人民币";
        for(int i=v.size()-1;i>=0;i--){
            for(int j=3;j!=-1;j--){//对一组中4位分别输出
                int bit=v[i]/(int)pow(10,j);
                if(bit){
                    if(!(j==1&&bit==1))//防止输出"一十五"的情况
                       cout<<h1[bit];
                   cout<<h2[j];    //千、百、十
                }
                v[i]%=(int)pow(10,j);
            }
            cout<<h3[i];    //亿、万、元
        }
        if(deci){
            if(deci/10)    //角
                cout<<h1[deci/10]<<h3[3];
            if(deci%10) //分
                cout<<h1[deci%10]<<h3[4];
        }
        else    //整
            cout<<h3[5];
        cout<<endl;
    }
    return 0;
}

编辑于 2019-06-24 23:32:18 回复(2)
#include <bits/stdc++.h>

using namespace std;

string money[11] = {"零","壹","贰","叁","肆","伍","陆","柒","捌","玖","拾"};

void Print(int n)
{     int q,b,s,g;     q = n/1000;     n -= q*1000;     b = n/100;     n -= b*100;     s = n/10;     n -= s*10;     g = n;          if(q!=0)         cout<<money[q]<<"仟";     if(b!=0)         cout<<money[b]<<"佰";     if(q!=0 && b==0)         cout<<money[b];     if(s!=0){         if(s!=1)             cout<<money[s]<<"拾";         else             cout<<"拾";     }     if(b!=0 && s==0)         cout<<money[s];     if(g!=0)         cout<<money[g];
}

int main()
{     double m;     while(cin>>m)     {         m += 0.005;         cout<<"人民币";         int n;         n = m/100000000;         m -= n*100000000;         if(n!=0){             Print(n);             cout<<"亿";         }                  n = m/10000;         m -= n*10000;         if(n!=0){             Print(n);             cout<<"万";         }                  n = (int)m;         m -= n;         if(n!=0){             Print(n);             cout<<"元";         }                  m = m*100;         int j = m/10;         int f = m-j*10;         if(j!=0)             cout<<money[j]<<"角";         if(f!=0)             cout<<money[f]<<"分";         cout<<endl;         }     return 0;
} 

发表于 2018-07-19 23:01:25 回复(0)
//将阿拉伯数字的金额转化为汉字的人民币金额
import java.util.Scanner;
 public class Main{
public static void main(String[] args){
final String[] st = {"零","壹","贰","叁","肆","伍","陆","柒","捌","玖"};
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
Double money = sc.nextDouble();
StringBuffer stb = new StringBuffer();
int yi = (int)(money/100000000);
int wan = (int)((money%100000000)/10000);
int yuan = (int)(money%10000);
//取余数运算有问题这里,所以加上0.001
int xiaoshu=(int) ((money - yi * 100000000 - wan * 10000 - yuan + 0.001) * 100);
        int xiao=xiaoshu/10;
        int shu =  (int)((money%1+0.001)*100%10);
System.out.print("人民币");
if(yi != 0){
stb.append(change(yi) + "亿");
}
if(wan != 0){
stb.append(change(wan) + "万");
}
if(yuan != 0){
stb.append(change(yuan) + "元");
}
if(xiao == 0 && shu == 0){
stb.append("整");
}else if(xiao != 0 && shu != 0){
stb.append(st[xiao] + "角" + st[shu] + "分");
}else if(xiao != 0 && shu == 0){
stb.append(st[xiao] + "角");
}else{
stb.append(st[shu] + "分");
}
 String moni = stb.toString();
 System.out.println(moni);
}
sc.close();
}
 
  public static String change(int db){
  final String[] st = {"零","壹","贰","叁","肆","伍","陆","柒","捌","玖"};
  StringBuffer stb = new StringBuffer();
  int qian = db/1000;
  int bai = (db%1000)/100;
  int shi = (db%100)/10;
  int ge = (db%10);
  if(qian != 0){
  stb.append(st[qian] + "仟");
  }
  if(bai != 0){
  stb.append(st[bai] + "佰");
  }else if(qian != 0 && bai == 0 &&(shi != 0 || ge != 0) ){
  stb.append("零");
  }
  if(shi != 0 && shi != 1){
  stb.append(st[shi] + "拾");
  }else if(qian ==0 && bai == 0 && shi != 0 && shi == 1){
  stb.append("拾");
  }else if((qian != 0 || bai != 0) && shi != 0 && shi == 1){
  stb.append(st[shi] + "拾");
  }
  if(ge != 0)
  {
  stb.append(st[ge]);
  }
  String str = stb.toString();
  return str;
  }
 }
发表于 2017-09-11 15:10:22 回复(0)