| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 1716 人关注过本帖
标题:把数字转换为单词
取消只看楼主 加入收藏
madfrogme
Rank: 20Rank: 20Rank: 20Rank: 20Rank: 20
等 级:版主
威 望:21
帖 子:1160
专家分:1106
注 册:2009-6-24
结帖率:98.63%
收藏
 问题点数:0 回复次数:0 
把数字转换为单词
把数字转换为单词
来源
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
快速回复:把数字转换为单词
数据加载中...
 
   



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

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