算法取号,并输出其英文单词 [英] Algorithm to take a number and output its English word

查看:236
本文介绍了算法取号,并输出其英文单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想打在C语言的程序,该程序会要求用户输入一个数字,然后将打印的英文这个数字。

I want to make a program in C which will ask the user to input a number and then it will print that number in English.

例如:

if(INPUT == 1) then print ONE
if(INPUT == 2) then print TWO

等。它可以使用开关的情况下进行,如果其他人,但它使code冗长。对于几个数字很不错,但如果我们必须写多达100那么这将是漫长的。

and so on. It can be made using switch-case and if else but it makes the code lengthy. For few numbers it's fine but if we have to write up to 100 then it will be lengthy.

有一个简短算法或想法呢?

Is there a short algorithm or idea for this?

推荐答案

您可以使用下面的,但这仅打印高达数千人。我这样做是为了解决某些特定的编程问题。这就是为什么我没有超出数千人。但它并不难扩大更大一些。此外,这个程序仍然可以优化或变得更清晰。

You can use the below, but this prints only upto thousands. I did this to solve some particular programming problem. Thats why i did not extend beyond thousands. But its not hard to extend for bigger number. Also, this program can be still optimized or made more clearer.

#include <stdio.h>
#include <string.h>

void print(int num) {
    char digit [21][10] = { "", "one", "two", "three", "four", "five", "six", "seven",
                          "eight", "nine", "ten", "eleven", "twelve", "thirteen", 
                          "fourteen", "fifteen", "sixteen", "seventeen", "eighteen",
                          "nineteen"};
    char tens [11][10] = { "", "", "twenty", "thirty", "forty", "fifty", "sixty", 
                         "seventy", "eighty", "ninety"};
    char str[1000] = {0};
    int prev=0, div=1000;
    strcpy(str, "");

    while(div) {

        if ((num / div) % 10 > 0 || (div == 10 && (num%100) > 0)) { 

            if (prev) {
                strcat(str, "and");
                prev = 0;
            }

            switch(div) {
            case 1000:
                strcat(str, digit[(num / div) % 10]);     
                strcat(str, "thousand");
                prev = 1;
                break;
            case 100:
                strcat(str, digit[(num / div) % 10]);     
                strcat(str, "hundred");
                prev = 1;
                break;
            case 10:
                if ( (num%100) >= 10 && (num%100) <= 19)
                    strcat(str, digit[num%100]);
                else {
                    strcat(str, tens[(num%100)/10]);
                    strcat(str, digit[num%10]);
                }
                break;
            }
        }

        div /= 10;
    }
    printf("%d %s\n", num, str);

}
int main(int argc, char **argv) {

    long sum = 0;
    int count = 0;

    if (argc <= 1) {
        fprintf(stderr, "wrong number of arguments\n");
        return -1;
    }

    print(atoi(argv[1]));

    return 0;
}

这篇关于算法取号,并输出其英文单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆