题目要求
请实现一个函数, 输入一个小于100000000(一亿)的自然数,并在屏幕上打印这个数字的中文写法。
例如:17 —> 一十七 120 —> 一百二十 201 —> 二百零一
1074 —> 一千零七十四 2001 —> 二千零一
提示:请注意‘零’的处理。
代码实现
#include <iostream>
#include <string>
using namespace std;
void intToChinese(unsigned int num)
{
string s[9] = { "","十","百","千","万","十","百","千","亿" };
string ch[10] = { "零", "一", "二", "三", "四", "五", "六", "七", "八", "九" };
int count = 0; // 记录输入的数字num有多少位数
int a[10] = { 0 }; // 记录输入数字每一位上的数字(1亿最多有10位数)
int index = 0; // 表示数组a的下标
while (num != 0) {
a[count] = num % 10;
num = num / 10;
count++;
}
if (1 == count) {
cout << ch[a[0]];
}
index = count - 1; // 输入数字的位数多于1位
while (index >= 0)
{
if (a[index] != 0) {
cout << ch[a[index]] << s[index];
index--;
} else {
while (index >= 0 && 0 == a[index]) {
// 为了打出万字
if (4 == index && (a[5] + a[6] + a[7] != 0)) {
cout << s[4];
}
index--;
}
if (index >= 0) {
cout << "零";
}
}
}
}
int main()
{
int test = 10086;
intToChinese(test);
return 0;
}
VS2017中运行结果如下: