标签:style blog io ar color 使用 sp for on
《C和指针》第7章第6道编程题:
编写函数
void written_amount( unsigned int amount, char *buffer );
它把 amount 表示的值转换为单词形式,并存储于 buffer 中。这个函数可以在一个打印支票的程序中使用。例如,如果 amount 的值是 16 312,那么 buffer 中存储的字符串应该是
SIXTEEN THOUSAND THREE HUNDRED TWELVE
调用程序保证 buffer 缓冲区的空间足够大。例如,1 200 可以是 ONE THOUSAND TWO HUNDRED 或 TWELVE HUNDRED。你可以选择一种你喜欢的形式。
1 /* 2 ** 把非负整数数值转化为单词形式 3 */ 4 5 #include <stdio.h> 6 #include <string.h> 7 8 void written_amount( unsigned int amount, char *buffer ); 9 10 int 11 main() 12 { 13 unsigned int num; 14 scanf( "%u", &num ); 15 char b[100] = { 0 }; 16 17 written_amount( num, b ); 18 19 puts( b ); 20 21 return 0; 22 } 23 24 /* 25 ** 函数功能:把amount的值转化为单词形式,结果存储在buffer中 26 */ 27 void 28 written_amount( unsigned int amount, char *buffer ) 29 { 30 /* 31 ** 数字对应的单词,分为4组 32 */ 33 char word_1_9[10][6] = { "ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE", 34 "SIX", "SEVEN", "EIGHT", "NINE" }; 35 char word_10_19[10][10] = {"TEN", "ELEVEN", "TWELVE", "THIRTEEN", "FOURTEEN", "FIFTEEN", 36 "SIXTEEN", "SEVENTEEN", "EIGHTEEN", "NINETEEN" }; 37 char word_ty[10][8] = { "", "", "TWENTY", "THIRTY", "FORTY", "FIFTY", 38 "SIXTY", "SEVENTY", "EIGHTY", "NINETY" }; 39 char word_div[4][9] = { "HUNDRED", "THOUSAND", "MILLION", "BILLION" }; 40 41 static int count = 0; // 记录千分位的个数 42 unsigned int tmp = amount / 1000; 43 44 /* 45 ** 用递归函数,直到数值< 1000 46 */ 47 if( tmp ) 48 { 49 count ++; // 千分位的个数增加 50 written_amount( tmp, buffer ); // 递归,处理下一个千分位 51 } 52 53 int val = amount % 1000; // 3位3位地进行转化单词 54 55 /* 56 ** 值大于100,先把百位上的数的单词存到buffer中 57 ** 后面加上 HUNDRED 58 ** 把值%100,变成两位数,后续继续处理 59 */ 60 if( val >= 100 ) 61 { 62 strcat( buffer, word_1_9[ val / 100 ] ); 63 strcat( buffer, " " ); 64 strcat( buffer, word_div[ 0 ] ); 65 val %= 100; 66 } 67 68 /* 69 ** 值在20至99之间,先把几十对应的单词加到buffer中 70 ** 再%10,后续处理个位上的数 71 */ 72 if( val >= 20 && val <= 99 ) 73 { 74 strcat( buffer, " " ); 75 strcat( buffer, word_ty[ val / 10 ] ); 76 val %= 10; 77 } 78 79 /* 80 ** 值在10到19之间,直接把对应的单词加到buffer中 81 */ 82 if( val >= 10 && val <= 19 ) 83 { 84 strcat( buffer, " " ); 85 strcat( buffer, word_10_19[ val % 10 ] ); 86 } 87 88 /* 89 ** 值在0到9之间,把对应的单词加到buffer中 90 */ 91 if( val >= 0 && val <= 9 ) 92 { 93 strcat( buffer, " " ); 94 strcat( buffer, word_1_9[ val ] ); 95 } 96 97 /* 98 ** 一个千位处理完后,后面加上对应的分位单词"THOUSAND"、"MILLION"等 99 */ 100 if( count > 0 ) 101 { 102 strcat( buffer, " " ); 103 strcat( buffer, word_div[ count-- ] ); 104 strcat( buffer, " " ); 105 } 106 }
标签:style blog io ar color 使用 sp for on
原文地址:http://www.cnblogs.com/zouhongmey/p/4122109.html