全局常量的声明
const char * chnNumChar [10] = {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"}; const char * sectionChar [4] = {"", "万", "亿", "万亿"}; const char * weightChar [4] = {"", "十", "百", "千"}; typedef long long ILONG;
转化四位及其四位以下的整数
string section2chn(ILONG onum) { string res(""); int weightindex = 0; bool iszero = false; while (onum > 0) { if (onum % 10) res = string(chnNumChar[onum % 10]) + weightChar[weightindex] + (iszero?chnNumChar[0]:"") + res; else if (!res.empty()) iszero = true; ++ weightindex; onum /= 10; } return res; }
转化整数
string num2chn(ILONG onum) { string res(""); int sectionindex = 0; bool isneedzero = false; while (onum > 0) { if (onum % 10000) res = section2chn(onum % 10000) + sectionChar[sectionindex] + (isneedzero?chnNumChar[0]:"") + res; else if (!res.empty()) isneedzero = true; if (onum % 10000 < 1000) isneedzero = true; ++ sectionindex; onum /= 10000; } return res; }
测试
#include <iostream> #include <string> #include <random> int main() { ILONG temnum = 6000000181; cout << temnum << " " << num2chn(temnum) << endl; random_device rd; for (int i = 0; i < 1000; ++ i) { ILONG temnum = rd() ; cout << temnum << " " << num2chn(temnum) << endl; } return 0; }