|
- // NumberToWords.cpp : Defines the entry point for the console application.
- //
- #include
- #include
- static char *digits[] = {
- "", "ONE ", "TWO ", "THREE ", "FOUR ", "FIVE ", "SIX ", "SEVEN ",
- "EIGHT ", "NINE ", "TEN ", "ELEVEN ", "TWELVE ", "THIRTEEN ",
- "FOURTEEN ", "FIFTEEN ", "SIXTEEN ", "SEVENTEEN ", "EIGHTEEN ",
- "NINETEEN "
- };
- static char *tens[] = {
- "", "", "TWENTY ", "THIRTY ", "FORTY ", "FIFTY ", "SIXTY ", "SEVENTY ",
- "EIGHTY ", "NINETY "
- };
- static char *magnitudes[] = {
- "", "THOUSAND ", "MILLION ", "BILLION "
- };
- static void do_one_group(unsigned int amount,char *buffer,char **magnitude)
- {
- int value;
- value=amount/1000;
- if(value>0)
- do_one_group(value,buffer,magnitude+1); //使用递归调用
-
- amount%=1000;
- value=amount/100;
- if(value>0)
- {
- strcat(buffer,digits[value]); //不同时间,不同函数中需要想字符串中加入新的字符
- strcat(buffer,"HANDREDS ");
- }
- value=amount%100;
- if(value>=20)
- {
- strcat(buffer,tens[value/10]);
- value=amount%10;
- }
- if(value>0)
- strcat(buffer,digits[value]);
- if ( amount>0 )
- strcat(buffer,*magnitude);
- }
- void written_amount( unsigned int amount,char * buffer)
- {
- if ( amount == 0 )
- {
- strcpy(buffer,"ZERO");
- }
- else
- {
- *buffer='\0';
- do_one_group(amount,buffer,magnitudes);
- }
- }
- int main(int argc, char* argv[])
- {
- unsigned int check=1234;
- char buffer[100];
- written_amount(check,buffer);
- puts(buffer);
- return 0;
- }
复制代码 为嘛代码编辑的时候不能缩进呢?
题目要求也是要将输入的数值转换为单词的形式打印出来。
先把我的程序贴出来,大致思路是这样的:
1.先建立几个数组,把相关的数值的单词形式存贮起来,这些数组使用频繁而且空间占用庞大,故使用静态存储方式,然后用数组下标遍历相应单词;
2.由于检测输入的时候是从高位到低位,输出的时候就可以用在高位输出没完成的时候不能输出低位,
故可以使用递归调用,将中间值存贮在堆栈中,实现从高位到底为依次输出;
3.创建字符串,将每次翻译出来的单词依次连起来,该判断条件的时候判断条件,最后调用puts函数输出;
4.使用函数实现模块化设计,确定不是空字符之后再调用处理函数,否则,输出buffer的初值‘\0’;
|
|