| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 1720 人关注过本帖
标题:把数字转换为单词
只看楼主 加入收藏
madfrogme
Rank: 20Rank: 20Rank: 20Rank: 20Rank: 20
等 级:版主
威 望:21
帖 子:1160
专家分:1106
注 册:2009-6-24
结帖率:98.63%
收藏
 问题点数:0 回复次数:1 
把数字转换为单词
把数字转换为单词
来源
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
搜索更多相关主题的帖子: return include function 单词 
2012-12-08 20:41
pangding
Rank: 19Rank: 19Rank: 19Rank: 19Rank: 19Rank: 19
来 自:北京
等 级:贵宾
威 望:94
帖 子:6784
专家分:16751
注 册:2008-12-20
收藏
得分:0 
学习了。这也小程序不支持4位数以上的,但有些技巧还是可以学学。
其实翻译数字的逻辑还是挺复杂的,我刚开始学C的时候想写来着,后来感觉没思路。翻译成中文容易一点。
2012-12-11 12:27
快速回复:把数字转换为单词
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.050445 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved