转换算法(中文数字转阿拉伯数字)

该博客详细介绍了将中文数字转化为阿拉伯数字的算法,包括关键的权位理解及三条转换规则:以10000为单位划分,小节内非0数字间用0间隔,千位为0时根据前一节判断0的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题解:
1.权位:如一千二百三十 1的权位是千,节以万为节

规则1:以10000为小节,小节的结尾即使是0,不使用0,
规则2:小节内两个非0的数之间使用0
规则3:当小节的千位事0,若小节的前一小节若无其他数字,则不用0,否则就要用0;

代码:

#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;

const char *chnNumChar[10] = {"零","一","二","三","四","五","六","七","八","九"};
const char *chnUnitSection[] = {"","万","亿","亿万"};
const char *chnUnitChar[] = {"","十","百","千"};//节权位

void sectionToChinese(unsigned int section,string &chnStr);
void numberToChinese(unsigned int num,string &chnStr)
{
    int unitPos =0;
    string strIns;
    bool needZero = false;

    while(num > 0)
    {
        unsigned int section = num % 10000; // 以10000为一节;每一节的数.
        if(needZero)
        {
            chnStr.insert(0,chnNumChar[0]);
        }
        sectionToChinese(section,strIns);
        //是否需要节权位
        strIns += (section != 0) ? chnUnitSection[unitPos] : chnUnitSection[0];

        chnStr.insert(0,strIns);
        //千位是0,需要在下一个section 补0;
        needZero = (section < 1000) && (section > 0);

        num /= 10000;
        unitPos++;
    }
}

//判断千位数字的。
void sectionToChinese(unsigned int section,string &chnStr)
{
    string strIns;
    int unitPos = 0;
    bool zero = true;
    while(section > 0)
    {
        int v = section % 10;
        if(v == 0)
        {
            if(section == 0 || !zero)
            {
                zero = true; // zero 的作用是确保连续多个0只补中间一个0;
                chnStr.insert(0,chnNumChar[v]);
            }
        }
        else
        {
            zero = false; //至少一个数字不是0
            strIns = chnNumChar[v]; // 此位对应中文数字
            strIns += chnUnitChar[unitPos];
            chnStr.insert(0,strIns);
        }

        unitPos++;
        section = section / 10;
    }
}


int main()
{
    string str;
    numberToChinese(1002,str);
    cout << str <<endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值