C++ 程序,其作用是将输入的阿拉伯正整数转换为中文数字表示形式
#include <iostream>
#include <string>
#include <vector>
// 定义中文数字字符和单位的向量(数组)
const std::vector<std::string> chineseNumbers = {
"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"
};
const std::vector<std::string> chineseUnits = { "", "十", "百", "千" };
const std::vector<std::string> chineseBigUnits = { "", "万", "亿", "兆" };
// 定义一个函数,将不超过1000的整数转换成中文数字字符串
std::string ConvertLessThanThousand(int num) {
std::string str;
for (int i = 0; num > 0 && i < 4; ++i) {
if (num % 10 > 0) {
if (i > 0) {
// 为当前位数添加中文数字和单位
str = chineseNumbers[num % 10] + chineseUnits[i] + str;
}
else {
// 个位数不需要添加单位
str = chineseNumbers[num % 10] + str;
}
}
else if (!str.empty() && str.front() != chineseNumbers[0][0]) {
// 如果当前位是零并且字符串不是以"零"开头,则添加"零"
str = chineseNumbers[0] + str;
}
// 将数字除以10,右移一位继续处理
num /= 10;
}
return str;
}
// 定义一个函数,将任意长正整数转换为中文数字字符串
std::string NumberToChinese(long long num) {
if (num == 0) {
// 如果数字为0,直接返回"零"
return chineseNumbers[0];
}
std::string result;
int bigUnitPosition = 0;
while (num > 0) {
int part = num % 10000;
std::string partStr = ConvertLessThanThousand(part);
if (bigUnitPosition > 0 && part > 0) {
// 为当前的四位数添加大单位(万,亿,等)
partStr += chineseBigUnits[bigUnitPosition];
}
// 添加已转换部分到结果变量
result = partStr + result;
// 将数字除以10000,左移四位继续处理
num /= 10000;
++bigUnitPosition;
}
return result;
}
int main() {
// 主函数,用于接收用户输入,并打印出转换结果
long long number = 0;
std::cout << "输入一个正整数:";
std::cin >> number;
std::string chinese = NumberToChinese(number);
std::cout << chinese << std::endl;
return 0;
}