取数字并输出其英文单词的算法

时间:2011-08-05 05:40:07

标签: c algorithm linguistics

我想在C中制作一个程序,要求用户输入一个数字,然后用英文打印该数字。

例如:

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

等等。它可以使用switch-case制作,如果是,但它会使代码冗长。对于少数数字它没关系,但如果我们必须写入100,那么它将是冗长的。

对此有简短的算法或想法吗?

9 个答案:

答案 0 :(得分:10)

您可以使用下面的内容,但最多只打印数千张。我这样做是为了解决一些特定的编程问题。这就是为什么我没有超过数千人。但不难扩大数量。此外,该程序仍然可以优化或更清晰。

#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;
}

答案 1 :(得分:3)

你可以使用它,它可以用来将前99个整数转换为单词。而且有点简单。看看:

void main()
{
int n,m,j;
clrscr();
printf("Enter any number between 1 to 99 : ");
scanf("%d",&n);
printf("You entered ");
if(n>0&&n<=10)
goto one;
else if (n>10&&n<20)
{
m=n%10;
goto two;
}
else if(n>20&&n<100)
{
j=n/10;
n=n%10;
goto three;
}
two:
switch(m)
{
case 1:printf("eleven ");
break;
case 2:printf("twelve ");
break;
case 3:printf("thirteen ");
break;
case 4:printf("fourteen ");
break;
case 5:printf("fifteen ");
break;
case 6:printf("sixteen ");
break;
case 7:printf("seventeen ");
break;
case 8:printf("eighteen ");
break;
case 9:printf("nineteen ");
break;
}
three:
switch(j)
{
case 2:printf("twenty ");
goto one;
case 3:printf("thirty ");
goto one;
case 4:printf("fourty ");
goto one;
case 5:printf("fifty ");
goto one;
case 6:printf("sixty ");
goto one;
case 7:printf("seventy ");
goto one;
case 8:printf("eighty ");
goto one;
case 9:printf("ninety ");
goto one;
}
one:
switch(n)
{
case 1:printf("one ");
break;
case 2:printf("two ");
break;
case 3:printf("three ");
break;
case 4:printf("four ");
break;
case 5:printf("five ");
break;
case 6:printf("six ");
break;
case 7:printf("seven ");
break;
case 8:printf("eight ");
break;
case 9:printf("nine ");
break;
case 10:printf("ten ");
break;
}
getch();
}

希望这有帮助。

答案 2 :(得分:3)

只需使用递归。我没有足够的时间来测试它,所以这段代码可能有些错误,但您可以轻松扩展它。

public static void convertNum(int number) {

    String[] digit = { "", "one", "two", "three", "four", "five", "six",
            "seven", "eight", "nine", "ten", "eleven", "twelve",
            "thirteen", "fourteen", "fifteen", "sixteen", "seventeen",
            "eighteen", "nineteen" };
    String[] tens = { "", "", "twenty", "thirty", "forty", "fifty",
            "sixty", "seventy", "eighty", "ninety" };

    if (number > 0 && number < 20)
        System.out.print(digit[number]);

    else if (number / 1000000 > 0) {

        convertNum(number / 1000000);
        System.out.print(" million ");
        convertNum(number % 1000000);

    }

    else if (number / 100000 > 0) {

        convertNum(number / 100000);
        System.out.print(" lukh ");
        convertNum(number % 100000);

    }

    else if (number / 1000 > 0) {

        convertNum(number / 1000);
        System.out.print(" thousand ");
        convertNum(number % 1000);

    }

    else if (number / 100 > 0) {

        convertNum(number / 100);
        System.out.print(" hundred ");
        convertNum(number % 100);

    }

    else if (number / 10 >= 2) {

        System.out.print(" " + tens[number / 10] + " ");
        convertNum(number % 10);

    }

}   

convertNum (9191197);

答案 3 :(得分:1)

我很难想出一种自动化这种方法的好方法,但仍然很简短。如果你知道终点(即你想要1-100),那么你可以这样做:

char* numberArray[101] = {'Zero', 'One', 'Two' ... , 'One Hundred'};

然后当你收到输入时,只需使用该数字来访问该数组索引,它就会吐出你的答案:

int input;
cin >> input; // input = 5
cout << numberArray[input]; // outputs: Five

我道歉,如果我的语法错误,我已经做了PHP和javaScript很长时间了,我现在还不记得C语法......

答案 4 :(得分:1)

你需要的是一个递归函数,它在一个,几十,一百和几千个数字之后自我调用。

例如。

num_to_string(num = 344384)
{
    if( haslakh())
    num_to_string(3);print("lakh");
    if( hasthou())
    num_to_string(44);print("thousand");
    if( hashundrer())
    num_to_string(38);print("hundred");
    num_to_string(4);
    if( num is from 1 to 9 ) print one..nine;
    if( num if from 10 to 90 ) print ten to ninty;
}

答案 5 :(得分:1)

如果人类没有实现千千万万(抱歉:1000),我会感到惊讶。

So I checked on Github and a found at least a few

我没有贡献任何一个。

答案 6 :(得分:0)

这是我写的,这很容易扩展到任何大小。我没有清理一些我能做的事情,但逻辑工作得非常好

import java.util.Arrays; import java.util.Scanner;

public class NumReader {

static final String[] units = {"", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
static final String[] tens = {"", null, "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
static final String[] teens = {"ten", "eleven", "twelve", "thrirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
static final String hundredSuffix = "hundred";
static final String[] suffixes = {"", "thousand", "million", "billion"};

static boolean isValid(int num) {
    return (num <= 1000000000 && num >= 0);
}
static String numToString(int inpNum) {
    return numToString(inpNum, String.valueOf(inpNum).toCharArray());
}
static String numToString(int inpNum, char[] digits) {
    return numToString(inpNum, digits, false);
}
static String numToString(int inpNum, char[] digits, boolean firstCall) {
    StringBuilder b = new StringBuilder();
    if (inpNum == 0 && firstCall) {
        return "zero";
    } else if (inpNum < 10) {
        return units[inpNum];
    } else if (inpNum < 20) {
        return teens[inpNum - 10];
    } else if (inpNum < 100) {
        b.append(tens[digits[0] - '0']).append(" ").append(units[digits[1] - '0']);
        return b.toString();
    } else if (digits.length == 3) {
        String sub = new String(Arrays.copyOfRange(digits, 1, 3));
        b.append(units[digits[0] - '0']).append(" ")
                .append(hundredSuffix);
        sub = numToString(Integer.parseInt(sub), Arrays.copyOfRange(digits, 1, 3));
        if (sub.equals("")) {
            b.append(sub);
        } else {
            b.append(" and ").append(sub);
        }
        return b.toString();
    } else if (digits.length > 3) {
        int numSuffixes = digits.length / 3;
        int initCut = digits.length % 3;
        int i;
        String sub, opt = "";
        for (i = 0; i < numSuffixes; i++) {
            int end = digits.length - 3 * i;
            sub = new String(Arrays.copyOfRange(digits, end - 3, end));
            sub = numToString(Integer.parseInt(sub));
            opt = (sub.equals("")) ? opt : (sub + " " + suffixes[i] + " " + opt);
        }
        if (initCut != 0) {
            sub = new String(Arrays.copyOfRange(digits, 0, initCut));
            opt = numToString(Integer.parseInt(sub)) + " " + suffixes[i] + " " + opt;
        }
        return opt;
    }
    return "";
}

public static void main(String[] args) {

    Scanner s = new Scanner(System.in);
    int num = s.nextInt();
    if (isValid(num)) {
        System.out.println(numToString(num, String.valueOf(num).toCharArray(), true));
    } else {
        System.out.println("Not a valid input, num <= 1000000000");
    }
}

}

答案 7 :(得分:0)

我想改善kalyan的答案。有2个错误:

  • 单词之间没有空格。例如:100将获得结果一百(无空格)
  • 英语中有成千上万的需要复数形式。例如200 - &gt;两百(它需要&#39; s&#39;结果)

像这样修改代码将解决这些错误:

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:
                if (strlen(str) > 0 && str[strlen(str) - 1] != ' ')
                    strcat(str, " ");
                strcat(str, digit[(num / div) % 10]);

                if (((num / div) % 10) > 1)
                    strcat(str, " thousands");
                else
                    strcat(str, " thousand");
                prev = 1;
                break;
            case 100:
                if (strlen(str) > 0 && str[strlen(str) - 1] != ' ')
                    strcat(str, " ");

                strcat(str, digit[(num / div) % 10]);

                if (((num / div) % 10) > 1)
                    strcat(str, " hundreds");
                else
                    strcat(str, " hundred");

                prev = 1;
                break;
            case 10:
                if ( (num%100) >= 10 && (num%100) <= 19)
                {
                    if (strlen(str) > 0 && str[strlen(str) - 1] != ' ')
                        strcat(str, " ");

                    strcat(str, digit[num%100]);
                }
                else {
                    if (strlen(str) > 0 && str[strlen(str) - 1] != ' ')
                        strcat(str, " ");
                    strcat(str, tens[(num%100)/10]);

                    if (strlen(str) > 0 && str[strlen(str) - 1] != ' ')
                        strcat(str, " ");

                    strcat(str, digit[num%10]);
                }
                break;
            }
        }

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

}

答案 8 :(得分:0)

这是另一种方式。不确定优点效率与内存与速度的关系,但很容易添加代码来处理更多数字。

/* File : num_to_words_int.c
*
*  Descr: Prints the equivalent number in words. '1' to 'one', etc.
*     This version takes the input and converts it to a numeric vs.
*     a string value. 345 vs. "345". Then uses modulus division to
*     count the number of digits. The count represents the places;
*     i.e. count=5 ==> 10,000 ,, 1,000 ,, 100 ,, 10 ,, 1 are the
*     words that will be needed.
* 
*     300  => count=3 ==>three hundred
*     30   => count=2 ==>thirtey
*     3    => count=1 ==>three
*     13   => count=2 ==>thirteen
*     3456 => count=4 ==>three thousand four hundred fifty six
*     
*     [345], [34 5], [3 4], [3, [0]
*
*  Debugging Option:
*    <run> num_to_words_int.exe number option_mask
*
*          001 - print init   remainder array
*          010 - print filled remainder array
*          100 - print count, index, remainder value
*
*  Author: Gene Bradshaw
*  Date:   09-16-2016     
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math>

void main(int argc, char *argv[])
{
  const int HUNDREDS=0, THOUSANDS=1, MILLIONS=2, BILLIONS=3;
  int i, count, total, remainder[12]={-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};
  long number=0, orignum=0;
  char *ones[]  = {"zero","one","two","three","four","five","six","seven","eight","nine"};
  char *teens[] = {"ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"};
  char *tens[] = {"ten","ten","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"};
  char *places[] = {"hundred","thousand","million","billion"};  // place values; 10's, 100'2, etc.


  // ERRORS ARGUMENTS
  if(argc < 2)
  {
    printf("\na number is required as input!\n\n");
    exit(1);
  }
  else if(argc > 3)
  {
    printf("\nonly one number and optionally a flag are required as input!\n\n");
    exit(1);
  }
    else  printf("\n");

    // CONVERT TO WORDS
    if(!(number = atol(argv[1])))   // zero
    {
        printf("number: %d\n%s\n\n", number, ones[0]);
        exit(0);
    }


  // Debugging
  if(argv[2] && (atoi(argv[2]) & 0x01))
    {
    for(i=11; i>-1; i--)    printf("%d %d, ", i, remainder[i]);
    printf("\n\n");
    }

  // GET DIGITS
    if(number < 0)  // Remeber if negative, then make positive
    {
        orignum = number;       number *= -1;
    }

   count=0;
  do{
    remainder[count++] = number%10;
    number/=10;
  }while(number); // int type var converts to '0' when # < 0

  // ERROR DIGIT COUNT
  if (count > 12) 
  {
    printf("\ntoo many digits; up to 12 digits supported!\n\n");
    exit(1);
  }

    // Debugging
  if(argv[2] && (atoi(argv[2]) & 0x02))
  {
        for(i=11; i>-1 ; i--)    printf("%d %d, ", i, remainder[i]);
    printf("\n\n");
    }


    // DISPLAY REMAINDERS
    printf("number: ");  // This if for displaying the reverse remainder[].
    if (orignum < 0) printf("-");

    for(i=count-1; i>-1; i--)
  {
    if(!(i%3) && i)  printf("%d,", remainder[i]);
    else    printf("%d", remainder[i]);
  }
  printf("\n");

    // FIND AND PRINT WORDS
  total = count; i = count-1;                          // counting rules
    if(orignum < 0)     printf("negative ");
  while(count)
  { 
    if(argv[2] && (atoi(argv[2]) & 0x04))              // Debugging
            printf("\nC: %d, i: %d and R: %d\n", count, i, remainder[i]);

    switch(count)
    {
      case 1: 
        // print if not teens or 0
        if(remainder[i+1] != 1 && remainder[i])
          printf("%s ", ones[remainder[i]]);
        break;
      case 2: 
        // teens when 2nd digit is a '1'
        if(remainder[i] == 1)
          printf("%s ", teens[remainder[i-1]]);

        // ones when 1st digit is not a '0'
        else if(remainder[i])
          printf("%s ", tens[remainder[i]]);

        break;
      case 3: // d
        if(remainder[i]){
          printf("%s ", ones[remainder[i]]);
          printf("%s ", places[count-3]);
        }
        break;
      case 4: // k
        if(remainder[i])
          printf("%s ", ones[remainder[i]]);

                if(remainder[i] || (total > 4 && total < 7))
          printf("%s ", places[count-3]);

                break;
      // 10,000   100,000  1,000,000
      // ten tho  hun tho  one million
      case  5: // 10 k
      case  8: // 10 M
      case 11: // 10 B
        if(remainder[i]){  printf("%s ", tens[remainder[i]]); }
        break;
      case  6: // 100 k
      case  9: // 100 M
      case 12: // 100 B
        if(remainder[i]){
          printf("%s ", ones[remainder[i]]); 
          printf("%s ", places[HUNDREDS]);
        }
        break;
      case  7: // M
       if(remainder[i])
          printf("%s ", ones[remainder[i]]);

       if(remainder[i] || (total > 7 && total < 10))
          printf("%s ", places[MILLIONS]);
              break;
      case 10: // B
       if(remainder[i])
          printf("%s ", ones[remainder[i]]);

       if(remainder[i] || (total > 10 && total < 13))
          printf("%s ", places[BILLIONS]);
        break;

            // Add cases to increase digit count supported
            //case 13: //T /*- add code here -*/ break;

            default: break;
    }
    count--; i--;
  }  
  printf("\n\n");
}

示例:

    $>./num_to_words.exe -1000000
    $>number: -1,000,000
    $>negative one million 

    $>./num_to_words.exe 123456789011
    $>number: 123,456,789,011
    $>one hundred twenty three billion four hundred fifty six million seven hundred eighty nine thousand eleven 

    $>./num_to_words.exe 123456789012
    $>number: 123,456,789,012
    $>one hundred twenty three billion four hundred fifty six million seven hundred eighty nine thousand twelve 

    $>./num_to_words.exe -123456789012
    $>number: -123,456,789,012
    $>negative one hundred twenty three billion four hundred fifty six million seven hundred eighty nine thousand twelve 

    $>./num_to_words.exe 0
    $>number: 0
    $>zero

    $>./num_to_words.exe 1
    $>number: 1
    $>one