将1亿以内的任意数字转换为中文输出
生活随笔
收集整理的這篇文章主要介紹了
将1亿以内的任意数字转换为中文输出
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目要求
請實現一個函數, 輸入一個小于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中運行結果如下:
總結
以上是生活随笔為你收集整理的将1亿以内的任意数字转换为中文输出的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 简洁优美的深度学习包-bert4kera
- 下一篇: 身体是本钱哪_悟sphenic_新浪博客