转换算法(中⽂数字转阿拉伯数字)
题解:
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)
{
cstring转为int
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;
return0;
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。