首页 > 试题广场 >

人民币转换

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

输出

人民币壹仟零拾元整
#include<iostream>
#include<string>
using namespace std;
const string num_s[10] = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
const string unit_s[9] = {"", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿"};
const string small_s[4] = {"角", "分"};
const string unit = "元";
const string inter = "整";
int main()
{
    double num_in;
    while(cin >> num_in) {
        int sm = (num_in - int(num_in)) * 100 + 0.5;
        string sm_str = "";
        if(sm == 0) 
            sm_str.append(inter);
        else {
            if(sm / 10 != 0)
                sm_str.append(num_s[sm / 10] + small_s[0]);
            if(sm - sm / 10 * 10 != 0)
                sm_str.append(num_s[sm - sm / 10 * 10] + small_s[1]);
        }
        int dit = num_in;
        string dit_str = "人民币";
        string dit_trans = to_string(dit);
        int dit_len = dit_trans.length();
        bool zero_flag = false;
        for(int i = 0; i < dit_len; i ++) {
            if(dit_trans[i] != '0') {
                if(zero_flag) {
                    dit_str.append(num_s[0]);
                    zero_flag = false;
                }
                if(!((dit_len - i) % 4 == 2 && dit_trans[i] == '1'))
                    dit_str.append(num_s[dit_trans[i] - '0']);
                dit_str.append(unit_s[dit_len - i - 1]);
            } else {
                zero_flag = true;
                if((dit_len - i) % 4 == 0) {
                    dit_str.append(unit_s[dit_len - i - 1]);
                    zero_flag = false;
                }
            }        
        }
        if(dit != 0)
            dit_str.append(unit);
        cout << dit_str + sm_str << endl;
    }
    system("pause");
    return 0;
}
//我是真的想吐槽题目反人类
发表于 2018-12-27 11:28:37 回复(3)
#include <iostream>
#include <cmath>
#include <string>
using namespace std;

const string chnNumChar[] = { "零","壹","贰","叁","肆","伍","陆","柒","捌","玖" };
const string chnUnitSection[] = { "","万","亿","万亿" };
const string chnUnitChar[] = { "","拾","佰","仟" };

void SectionToChinese(unsigned int section, string& chnStr)
{
	int uintPos = 0;
	bool zero = true;
	while (section > 0)
	{
		string strIns;
		int v = section % 10;
		if (v == 0)
		{
			if ((section == 0) || zero)
			{
				zero = true;
				chnStr.insert(0, chnNumChar[v]);
			}
		}
		else
		{
			zero = false;
			if (!(v == 1 && uintPos == 1)) // 壹拾->拾
				strIns = chnNumChar[v];
			strIns += chnUnitChar[uintPos];
			chnStr.insert(0, strIns);
		}
		uintPos++;
		section = section / 10;
	}
}

void NumberToChinese(unsigned int num, string& chnStr)
{
	int uintPos = 0;
	bool needZero = false;

	while (num > 0)
	{
		string strIns;
		unsigned int section = num % 10000;
		if (needZero)
			chnStr.insert(0, chnNumChar[0]);

		SectionToChinese(section, strIns);
		strIns += (section != 0) ? chnUnitSection[uintPos] : chnUnitSection[0];
		chnStr.insert(0, strIns);
		needZero = (section < 1000) && (section > 0);
		num = num / 10000;
		uintPos++;
	}
}

int main(void)
{
	string output;
	double input;
	double precious, ipart;
	while (cin >> input)
	{
		output.clear();
		precious = modf(input, &ipart);
		NumberToChinese((unsigned int)ipart, output);
		output.insert(0, "人民币");
		if (ipart > 0.001)
		{
			output.append("元");
		}
		if (precious > 0.001)
		{
			precious += 0.001;
			int pre_part = precious * 10;
			if (pre_part > 0)
				output.append(chnNumChar[pre_part] + "角");
			pre_part = (int)(precious * 100) % 10;
			if (pre_part > 0)
				output.append(chnNumChar[pre_part] + "分");
		}
		else
		{
			output.append("整");
		}

		cout << output << endl;
	}
	return 0;
}

发表于 2016-09-17 21:54:50 回复(2)
#include <bits/stdc++.h>
using namespace std;
string ones[]={"零","壹","贰","叁","肆","伍","陆","柒","捌","玖"};
string tens[]={"拾","佰","仟","万","亿"};
long it[]={(long)1e1,(long)1e2,(long)1e3,(long)1e4,(long)1e8};
string fun(long m){
    if( m < 10)
        return ones[m];
    else if(10<=m && m <100)
        return (m/10==1?"":ones[m/10]) + tens[0] + (m%10==0?"":fun(m%10));
    else{
        for(int i=2;i<=4;++i)
            if(m < it[i])
                return fun(m/it[i-1]) + tens[i-1] + fun(m%it[i-1]);
        return fun(m/it[4]) + tens[4] + fun(m%it[4]);
    }
}
string renminbi(double m){
    string money=to_string(m);
    int tenth=money[money.find_first_of('.')+1]-'0';
    int hundredth=money[money.find_first_of('.')+2]-'0';
    if(tenth+hundredth==0)//整数
        return "人民币" + fun(long(m)) + "元整";
    else
        return "人民币" + (long(m)==0?"":fun(long(m)) + "元") + 
                 (tenth==0?"":ones[tenth] + "角") + 
                    (hundredth==0?"":ones[hundredth] + "分");
}
int main(){
    for(double m;cin >> m;)
        cout << renminbi(m) << endl;
    return 0;
} 

这种题目最适合用递归啦😑

编辑于 2020-06-28 00:04:09 回复(3)
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)
正头像
import java.util.Scanner;
public class Main{
    
    static String[] map = {"壹","贰","叁","肆","伍","陆","柒","捌","玖"};
	
    public static void main(String[] args){
    	 Scanner scan = new Scanner(System.in);
         while(scan.hasNext()){
             String number = scan.next();
             resolve(number);
         }
         scan.close();
    }
    
    public static void resolve(String str){

        String[] strArr = str.split("\\.");
        int number = Integer.valueOf(str.split("\\.")[0]);
       
        StringBuffer res = new StringBuffer("人民币");
        int yi = (int)(number/100000000);
        if(yi!=0){
            res.append(resolveQian(yi)).append("亿");
            number = number-yi*100000000;
        }
        
        int wan = (int)(number/10000);
        if(wan!=0){
            res.append(resolveQian(wan)).append("万");
          	number = number-wan*10000;
        }
        
         //处理千百十个位
        String beforePointString = resolveQian(number);
        if(beforePointString.length()>1){
        	 res.append(beforePointString).append("元");
        }
        
        //若有小数点,处理小数点后面位数
        if(strArr.length>1){
        	 String afterPointStr = strArr[1];
             //System.out.println(afterPointStr);
             res.append(handleNumberAfterPoint(afterPointStr));
        }
        
        //在resolveQian() 方法里可能会返回  零xxx 
        //但在最高为不能有"零"
        String resString = res.toString();
      
        if(resString.length()>4 && resString.charAt(3)=='零' && resString.charAt(4)!='元'){
    	   //System.out.println(resString.substring(0,3));
        	resString = resString.substring(0,3)+resString.substring(4);
        }

        System.out.println(resString);
        
    }
    
    //处理4位数 千百十个位
   	public static String resolveQian(double temp){
   
   		StringBuffer resBuffer = new StringBuffer();
   		
   		//千位
   		int qian = (int)(temp/1000);
   		if(qian!=0){
   			resBuffer.append(map[qian-1]).append("仟");
   			temp = temp-qian*1000;
   		}
   		
   		//百位
   		int bai = (int)(temp/100);
   		if(bai!=0){
   			resBuffer.append(map[bai-1]).append("佰");
   			temp = temp-bai*100;
   		}
   		//注意:零 只会添加在 百位和十位
   		if(qian!=0 && bai==0){
   			resBuffer.append("零");
   		}
   		
   		//十位
   		int shi = (int)(temp/10);
   		if(shi!=0){
   			if(shi!=1){
   				resBuffer.append(map[shi-1]);
   			}
   			resBuffer.append("拾");
   			temp = temp-shi*10;
   		}
   		
   		//注意:0
   		if(bai!=0&&shi==0){
   			resBuffer.append("零");
   		}
   		
   		//个位
   		int ge = (int)(temp%10);
   		
   		
   		if(ge!=0){
   			//5,0001 这种情况,千百十位均为0
   			if(qian==0&&bai==0&&shi==0){
   				resBuffer.append("零");
   			}
   			resBuffer.append(map[ge-1]);
   		}
   		String res = resBuffer.toString();
        return res;
    }
   	
   	//处理小数点后面的数
   	public static String handleNumberAfterPoint(String str){
   		String res = "";
   		if(str.equals("00") ||str.equals("0")){
   			res = "整";
   		}else{
   			if(str.charAt(0)!='0'){
   				res += map[Integer.valueOf(str.charAt(0)+"")-1]+"角";
   			}
   			if(str.length()>1 && str.charAt(1)!='0'){
   				res += map[Integer.valueOf(str.charAt(1)+"")-1]+"分";
   			}
   		}
   		return res;
   	}
}


编辑于 2016-08-20 21:48:58 回复(0)
这题考试的时候不给测试用例大罗神仙也不可能通过率100%吧,边界条件太复杂,好多还是模棱两可的就看答案怎么定了
#include<iostream>
#include<string>
using namespace std;
void dealInterger(string str);
void dealDecimal(string str);
string flag1[]={"","壹","贰","叁","肆","伍","陆","柒","捌","玖"};
string flag2[]={"仟","佰","拾",""};
int main(){
    string st;
    while(getline(cin,st)){
        string st1,st2;
        st1=st.substr(0,st.length()-3);//st1-整数部分
        st2=st.substr(st.length()-2);//st2-小数部分
        //cout << st1 << ' ' << st2 << endl;
        cout << "人民币";
        dealInterger(st1);
        if(st1!="0")
            cout << "元";
        dealDecimal(st2);
        cout << endl;
    }
    return 0;
}
void dealInterger(string str){  //整数部分
    if(str=="0"){  //整数部分为0“0.15没有零元”
        return;
    }
    if(str.length()>8){  //亿以上
        string temp=str.substr(0,str.length()-8);
        dealInterger(temp);
        cout << "亿";
        str=str.substr(str.length()-8);
    }
    if(str.length()>4){  //万以上
        string temp=str.substr(0,str.length()-4);
        //cout << temp << endl;
        dealInterger(temp);
        cout << "万";
        str=str.substr(str.length()-4);
    }
    for(int i=0,j=4-str.length();i<str.length();++i,++j){  //万以内
        if(i==0 && str.length()==2 && str[i]=='1'){ //两位且首位为1 “10拾不是壹拾”
            cout << "拾";
            continue;
        }
        if(str[i]=='0'){
            cout << "零";
            while(str[i+1]=='0')
                ++i,++j;
        }
        else{
            cout << flag1[str[i]-'0'];//数字
            cout << flag2[j];//位标
        }
    }
}
void dealDecimal(string str){   //小数部分
    if(str=="00"){
        cout << "整";
        return;
    }
    if(str[0]!='0'){
        cout << flag1[str[0]-'0'];//数字
        cout << "角";//位标
    }
    if(str[1]=='0')
        return;
    else{
        cout << flag1[str[1]-'0'];//数字
        cout << "分";//位标
    }
}


发表于 2019-09-14 18:07:08 回复(0)
#include<iostream>
#include<vector>
#include<iomanip>

using namespace std;
string s1(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 "玖";
	default:
		break;
	}
}

string s2(int i)
{
	switch (i)
	{
	case 0:
		return "元";
	case 1:
		return "拾";
	case 2:
		return "佰";
	case 3:
		return "仟";
	case 4:
		return "万";
	case 5:
		return "亿";
	default:
		break;
	}
}

/*
具体方法:分为小数部分和整数部分,从最后一位开始向前遍历,装到vector<string>中,
          然后倒序输出

小数部分:把小数部分扩大100倍,变为2位整数,分3种情况,判断即可。
整数部分:①定义一个len表示当前遍历的位置,然后用整数Inte对10取余,
          可以得到最后一位,然后再将Inte除以10,删除最后一位。
          当len = 0时,输出“元”,当len / 4后对2取余,如果是1,
          则表示该位是万位,如果是2,则表示是亿位。其他情况直接对4取余,
          然后判断余数即可。
     
          ②还需要考虑输入数字第一位是1且在“拾”的位置上的情况,
          不能直接输出壹,如15 应该是拾伍,而不是壹拾伍。
     
          ③每次循环开始前,先把上一次的now赋给bef,如果本次循环
          的now==0,且bef==0,则不输出零和单位,如果now==0,bef!=0,
          则只输出零。
            
     每操作完一位最后,再进行len++。 */
void DoutoRMB(double m)
{
	int len = 0;					//整数部分长度
	int Inte = (int)m;				//整数部分
	vector<string> arr;

	//小数部分
	int Rem = (m - Inte + 0.001) * 100;	//小数部分扩大100倍变为整数
	if (Rem == 0)
		arr.push_back("整");          //小数部分为0,输出 “整”
	else if (Rem % 10 == 0 && Rem / 10 != 0)
	{
		arr.push_back("角");
		arr.push_back(s1(Rem / 10));
	}
	else if (Rem % 10 != 0 && Rem / 10 == 0)
	{
		arr.push_back("分");
		arr.push_back(s1(Rem % 10));
	}
	else
	{
		arr.push_back("分");
		arr.push_back(s1(Rem % 10));
		arr.push_back("角");
		arr.push_back(s1(Rem / 10));
		
	}

    //整数部分
	int now = -1;    //双“指针”,分别指向整数中当前位置
	int bef = -1;    //和上一个位置,用于连续0的判断
    
	while (Inte)
	{
		bef = now;
		now = Inte % 10;
		Inte /= 10;

		if (now != 0)
		{
			if (len == 0)
				arr.push_back(s2(0));
			else if (len % 4 == 0 && (len / 4) % 2 == 1)
				arr.push_back(s2(4));
			else if (len % 4 == 0 && (len / 4) % 2 == 0)
				arr.push_back(s2(5));
			else
				arr.push_back(s2(len % 4));

			if (Inte == 0 && now == 1 && len != 0 && len % 4 == 1)
				;
			else
				arr.push_back(s1(now));
		}	
		else if(now == 0 && bef == 0)
		{

		}
		else if (now == 0 && bef != 0)
		{
			arr.push_back(s1(now));
		}

		len++;
	}
	arr.push_back("人民币");



	//输出字符串
	for (vector<string>::iterator it = arr.end() - 1; it >= arr.begin(); it--)
	{
		cout << *it;
		if (it == arr.begin())
			break;
	}

}



int main()
{
	double temp;
    while(cin >> temp)
    {
        DoutoRMB(temp);
        cout << endl;
    }

	return 0;
}

编辑于 2020-07-04 20:08:57 回复(1)
1.和HJ42 学英语一样的思想,只不过英文以千,中文以万。
2. 主要差别在于加‘零’,不妨数量级差两位及以上就加‘零’,最后“‘零零’”replace“零”,再把头部的“零”去掉。
3. 需要注意整数位为0或小数为零的特殊情况
4. repalce 和 strip都不改变原数据,注意赋值!!
5. 不适用于万亿以上
n = '零,壹,贰,叁,肆,伍,陆,柒,捌,玖,拾,拾壹,拾贰,拾叁,拾肆,拾伍,拾陆,拾柒,拾捌,拾玖'.split(',')
q = '角,分'.split(',')
# 整数,100,1000,10000,逐级引用
def within100(num):
    tmp = []
    if num < 20:
        if num < 10:
            tmp.append("零")
        tmp.append(n[num])
    else:
        tmp.append(n[num//10])
        tmp.append('拾')
        if num%10 != 0:
            tmp.append(n[num%10])
    return tmp

def within1000(num):
    tmp = []
    if num < 100:
        tmp.append("零")
        tmp += within100(num)
    else:
        tmp.append(n[num//100])
        tmp.append("佰")
        if num%100 != 0:
            if num%100 < 10:
                tmp.append("零")
            tmp += within100(num%100)
    return tmp
    
def within10000(num):
    tmp = []
    if num < 1000:
        tmp.append("零")
        tmp += within1000(num)
    else:
        tmp.append(n[num//1000])
        tmp.append("仟")
        if num % 1000 != 0:
            if num % 1000 < 100:
                tmp.append("零")
            tmp += within1000(num%1000)
    return tmp
# 小数
def small(num):
    tmp = []
    for i in range(len(num)):
        if int(num[i]) !=0:
            tmp.append(n[int(num[i])])
            tmp.append(q[i])
    return tmp
    
while True:
    try:
        z1, z2 = input().split(".")
        z1 = int(z1)
    except:
        break
    else:
        # 整数
        fin = []
        a = z1 // 100000000
        b = (z1 // 10000) % 10000
        c = z1 % 10000
        if a > 0:
            fin += within10000(a)
            fin.append("亿")
        if b > 0:
            fin += within10000(b)
            fin.append("万")
        if c > 0:
            fin += within10000(c)

        if len(fin) > 0:
            fin.append("元")
        # 分数
        if int(z2) == 0:
            fin.append("整")
        else:
            fin += small(z2)
        final = "".join(fin)
        final = final.replace("零零","零")
        final = final.strip("零")
        print("人民币"+final)


发表于 2021-12-22 04:12:25 回复(2)
虽然过了,但是没考虑亿,还有十万不加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)