回 帖 发 新 帖 刷新版面

主题:数字转换成汉字

求助啊!
 输入一个阿拉伯数字,输出为相应的汉字。例如输入389,输出为三百八十九,例如输入89203,输出八万九千二百零三
  用C语言编写,并且有注释!
  我在这先谢谢大家了!

回复列表 (共1个回复)

沙发

#include <stdio.h>
#include <string.h>
char hznum[100];
char hzunit[15][3]={"","十","百","千","万","十","百","千","亿","十","百","千","万","十","百"};
char hzdigit[10][3]={"零","一","二","三","四","五","六","七","八","九"};
char numstr[20];
char *ReadNumByHZ(double v) {
    char *p,*d;
    int u,i;

    sprintf(numstr,"%.15lg",v);
    printf("%s\n",numstr);
    if ('-'==numstr[0]) {
        sprintf(hznum,"不支持读负数");
        return hznum;
    }
    p=strchr(numstr,'e');
    if (NULL!=p) {
        sprintf(hznum,"不支持读太大或太小的数");
        return hznum;
    }
    d=NULL;
    p=strchr(numstr,'.');
    if (NULL!=p) {
        p[0]=0;
        d=p+1;
    }
    u=strlen(numstr);
    hznum[0]=0;
    for (i=0;i<u;i++) {
        if ('0'==numstr[i] && 0!=((u-1-i)%4)) {
            sprintf(hznum,"%s%s",hznum,hzdigit[numstr[i]-'0']);
        } else {
            sprintf(hznum,"%s%s%s",hznum,hzdigit[numstr[i]-'0'],hzunit[u-1-i]);
        }
    }
    //printf("%s\n",hznum);
    u=strlen(hznum);
    for (i=0;i<u;i+=2) {
        if (0==strncmp(hznum+i,"零零",4)) {//多个连续的“零”改成一个“零”
            memmove(hznum+i,hznum+i+2,u-i-2+1);
            i-=2;
            u-=2;
        }
    }
    //printf("%s\n",hznum);
    if (0==strcmp(hznum+u-2,"零")) hznum[u-2]=0;//末尾“零”去掉
    //printf("%s\n",hznum);
    u=strlen(hznum);
    for (i=0;i<u;i+=2) {
        if (0==strncmp(hznum+i,"零万",4) || 0==strncmp(hznum+i,"零亿",4)) {//“万”“亿”前是“零”去掉
            memmove(hznum+i,hznum+i+2,u-i-2+1);
            u-=2;
        }
    }
    //printf("%s\n",hznum);
    if (NULL!=d) {
        sprintf(hznum,"%s点",hznum);
        i=0;
        while (1) {
            if (0==d[i]) break;
            sprintf(hznum,"%s%s",hznum,hzdigit[d[i]-'0']);
            i++;
        }
    }
    //printf("%s\n",hznum);
    return hznum;
}
void main() {
    printf("\n%s\n",ReadNumByHZ(130040600090.012));
}

我来回复

您尚未登录,请登录后再回复。点此登录或注册