将阿拉伯数字转化为中文大写是很简单很实用的功能,但由于0这个特殊数字的存在使得实现起来并非那么容易,实现这一功能的关键就是对0的正确处理。该程序是我几个月之前写成的,当时没有加注释,现在程序的实现细节基本忘光了,难以写出注释。只能凭自己模糊的印象大致部分地介绍一下思路和方法,当初思路中的细节已经无法回忆了,没有注释的代码大家只能将就看一下,能看懂最好看不懂也没办法
我当初的想法是现将输入的阿拉伯数字的每一位单独分离出来,按从低位到高位的顺序存放在线性链表里,然后从低位到高位扫描链表。将数字从低位至高位每四位分为一组,最左边的组可以不足位。用Re代表每组中某数字相对于该组最低位的偏移量,di代表每组中最低起始位从数字最低位数起的的位数,从低位至高位从1起以4为间隔依次增大。用mark表示前一位是否为0,用sign表示某数右边低位部分是否全为0,flag表示每组中某数右边在该组中的低位部分是否全为0。程序中用字符型二维数组存放中文大写数字单位,并用三个函数分别完成单位阿拉伯数字到中文大写数字,每组内的数字单位到中文大写,以及每组的最低起始位的数字单位到中文大写的转化
程序的主体部分就是用循环结构从左到右扫描存放数字各位的链表,扫描过程中把转化出的中文大写数字按由高位至低位的顺序插入另一个链表,扫描完毕后新链表中存放的就是转换结果,可以直接输出。
C语言代码如下:
1 #include <stdio.h> 2 #include <malloc.h> 3 4 struct output //存放中文大写单位或数字的结构体类型 5 { 6 char ch[3]; 7 struct output *next; 8 }; 9 struct output *head1, *psnew1, *p1; 10 typedef struct output output1; 11 12 void Num(output1 *p1, char *N, int wei); //函数注释见main后的函数定义部分 13 void Re(output1 *p1, char *R, int re); 14 void Di(output1 *p1, char *D, int di); 15 16 void main () 17 { 18 int t; 19 int sign, flag, mark; 20 int re, di; 21 22 char N[10][3]={"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"}; //用字符串数组存放中文大写数字和单位 23 char R[3][3]={"拾", "佰", "仟"}; 24 char D[3][3]={"万", "亿", "兆"}; 25 26 struct number //存放每一位数字的结构体类型 27 { 28 int wei; 29 struct number *next; 30 }; 31 struct number *head, *psnew, *p; 32 typedef struct number number1; 33 34 printf ("please input the number which you want to convert\n"); 35 scanf ("%d", &t); //输入要转换的阿拉伯数字 36 37 head=(number1 *)malloc (sizeof(number1)); 38 psnew=head; 39 head->next=NULL; 40 41 head1=(output1 *)malloc (sizeof(output1)); 42 psnew1=head1; 43 head1->next=NULL; 44 45 while (t!=0) //将输入的阿拉伯数字的各位分离,按从低位至高位的顺序从左至右存放在线性链表中 46 { 47 p=(number1 *)malloc (sizeof(number1)); 48 p->wei=t%10; 49 p->next=NULL; 50 psnew->next=p; 51 psnew=p; 52 t=t/10; 53 } 54 55 psnew=head->next; 56 sign=0; 57 flag=0; 58 59 if (psnew->wei) 60 mark=1; //重要变量的必要初始化 61 else 62 mark=0; 63 64 re=0; 65 di=1; 66 67 while (psnew!=NULL) //从左到右扫描链表,进行到中文大写的转化,转换结果存放在ouput类型的链表中 68 { 69 if (re==0) 70 { 71 if (psnew->wei==0) 72 { 73 if (sign==1) 74 { 75 if (flag==1) 76 { 77 p1=(output1 *)malloc (sizeof(output1)); 78 Num(p1, &N[0][0], 0); 79 p1->next=head1->next; 80 head1->next=p1; 81 } 82 } 83 84 flag=0; 85 if (mark==1) 86 mark=0; 87 re=re+1; 88 } 89 else 90 { 91 if (sign==0) 92 { 93 if (di==1) 94 { 95 p1=(output1 *)malloc (sizeof(output1)); 96 Num(p1, &N[0][0], psnew->wei); 97 p1->next=NULL; 98 head1->next=p1; 99 } 100 else 101 { 102 p1=(output1 *)malloc (sizeof(output1)); 103 Di(p1, &D[0][0], di); 104 p1->next=NULL; 105 head1->next=p1; 106 107 p1=(output1 *)malloc (sizeof(output1)); 108 Num(p1, &N[0][0], psnew->wei); 109 p1->next=head1->next; 110 head1->next=p1; 111 } 112 } 113 else 114 { 115 if (flag==0) 116 { 117 p1=(output1 *)malloc (sizeof(output1)); 118 Di(p1, &D[0][0], di); 119 p1->next=head1->next; 120 head1->next=p1; 121 122 p1=(output1 *)malloc (sizeof(output1)); 123 Num(p1, &N[0][0], psnew->wei); 12