注册 登录
编程论坛 Linux教室

把数字转换为单词

madfrogme 发布于 2012-12-08 20:41, 1727 次点击
把数字转换为单词
来源
http://www.


程序代码:
/* A function that prints given number in words

 * but only 4 digits is supported
 */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void convert_to_words(char *num) {
    int len = strlen(num);
    if(len == 0) {
        fprintf(stderr,"Empyt string\n");
        return;
    }
   

    if(len > 4) {
        fprintf(stderr,"Length more than 4 is not supported\n");
        return;
    }
    char *single_digits[] = {"zero","one","two","three","four",\
                            "five", "six","seven","eight","nine"};

    char *two_digits[] = {"","ten","eleven","twelve","thirteen",\
                         "fourteen","fifteen","sixteen","seventeen",\
                         "eighteen","nineteen"};

    char *tens_multiple[] = {"","","twenty","thirty","forty","fifty",\
                            "sixty","seventy","eighty","ninety"};

    char *tens_power[] = {"hundred","thousand"};

    printf("\n%s: ",num);

    if(len == 1) {
        printf("%s\n",single_digits[*num-'\0']);
        return;
    }

    while(*num != '\0') {
        if(len >=3) {
            if(*num - '\0' != 0) {
                printf("%s ",single_digits[*num - '0']);
                printf("%s ",tens_power[len - 3]);
            }
            len--;
        }
        else {
            if(*num == '1') {
                int sum = *num - '\0' + *(num+1)-'0'; /* 11 : 1+1: index is 2*/
                printf("%s\n",two_digits[sum]);
                return;
            }
            else if(*num == '2' && *(num+1) == '0') {
                printf("twenty\n");
                return;
            }
            else {
                int i = *num - '0';
                printf("%s ",i? tens_multiple[i]:"");
                ++num;
                if(*num != '0') {
                    printf("%s\n",single_digits[*num-'0']);
                }
            }
        }
        ++num;
    }
}

int main(void) {
    convert_to_words("9923");
    convert_to_words("523");
    convert_to_words("89");
    convert_to_words("1203");
    convert_to_words("1200");
    return 0;
}
比如
9923: nine thousand nine hundred twenty three
523: five hundred twenty three
89: eighty nine
8989: eight thousand nine hundred eighty nine
1 回复
#2
pangding2012-12-11 12:27
学习了。这也小程序不支持4位数以上的,但有些技巧还是可以学学。
其实翻译数字的逻辑还是挺复杂的,我刚开始学C的时候想写来着,后来感觉没思路。翻译成中文容易一点。
1