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

    xiaoxiao2021-03-25  193

    题解: 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; }
    转载请注明原文地址: https://ju.6miu.com/read-8511.html

    最新回复(0)