将1亿以内的任意数字转换为中文输出
生活随笔
收集整理的這篇文章主要介紹了
将1亿以内的任意数字转换为中文输出
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
題目要求
請(qǐng)實(shí)現(xiàn)一個(gè)函數(shù), 輸入一個(gè)小于100000000(一億)的自然數(shù),并在屏幕上打印這個(gè)數(shù)字的中文寫(xiě)法。
例如:17 —> 一十七 120 —> 一百二十 201 —> 二百零一
1074 —> 一千零七十四 2001 —> 二千零一
提示:請(qǐng)注意‘零’的處理。
代碼實(shí)現(xiàn)
#include <iostream> #include <string> using namespace std;void intToChinese(unsigned int num) {string s[9] = { "","十","百","千","萬(wàn)","十","百","千","億" };string ch[10] = { "零", "一", "二", "三", "四", "五", "六", "七", "八", "九" };int count = 0; // 記錄輸入的數(shù)字num有多少位數(shù)int a[10] = { 0 }; // 記錄輸入數(shù)字每一位上的數(shù)字(1億最多有10位數(shù))int index = 0; // 表示數(shù)組a的下標(biāo)while (num != 0) {a[count] = num % 10;num = num / 10;count++;}if (1 == count) {cout << ch[a[0]];}index = count - 1; // 輸入數(shù)字的位數(shù)多于1位while (index >= 0){if (a[index] != 0) {cout << ch[a[index]] << s[index];index--;} else {while (index >= 0 && 0 == a[index]) {// 為了打出萬(wàn)字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中運(yùn)行結(jié)果如下:
總結(jié)
以上是生活随笔為你收集整理的将1亿以内的任意数字转换为中文输出的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 简洁优美的深度学习包-bert4kera
- 下一篇: 身体是本钱哪_悟sphenic_新浪博客