实现如下函数:
void printInChinese(int num);
这个函数输入一个小于100000000(一亿)的正整数,并在屏幕上打印这个数字的中文写法。
例如:
17 -> 一十七
120 -> 一百二十
201 -> 二百零一
1074 -> 一千零七十四
65536 -> 六万五千五百三十六
1010101 -> 一百零一万零一百零一
提示:请注意‘零’的处理。
扩展:如果需要处理通用简化习惯,你将怎么处理,例如:
17 -> 十七
120 -> 一百二
#include <iostream> #include <string> using namespace std; string unite[5]={"","十","百","千","万"}; //单位 string num[10]={"零","一","二","三","四","五","六","七","八","九"}; //一个汉字占两个字节,另外再加一个' '字符. string func(int a) { int flag=0,tmp; string strtmp; string result; int atemp=a; //设定a的临时存储值,防止每次进入循环都进行末尾零的判断 while(a!=0) { while(atemp%10==0) { flag++; atemp/=10; a/=10; } tmp=a%10; if(tmp!=0) strtmp=num[tmp]+unite[flag]; else if(tmp==0) strtmp="零"; result=strtmp+result; a/=10; flag++; } return result; } string convert(int a) { string result,temp; if(a<100000) result=func(a); else { temp=func(a/10000); result=temp+ "万"+ func(a-a/10000*10000); } return result; } void main() { int num; string numstring; cout<<"please input the num: "; cin>>num; numstring=convert(num); cout<<"the convert result is: "<<numstring<<endl; }
更多参考:http://hi.baidu.com/luojunlz/item/a86ddcf52723dbd743c36a39