简体   繁体   English

C-尝试将输入的未指定数字转换为它们各自的单词

[英]C - Trying to convert an unspecified amount of digits entered into their respective individual words

I know this is somewhat similar to the program that converts digits to words using things like "Thousands", "Hundred", etc. However, I'm looking to take an integer of any size (such as 543210) and create an output of "Five Four Three Two One Zero". 我知道这有点类似于使用“千”,“百”等将数字转换为单词的程序。但是,我正在寻找任何大小的整数(例如543210)并创建输出“五四三二一零”。 I'm using a switch statement that I think I understand fully and have working. 我正在使用switch语句,我认为我完全理解并可以正常工作。 I am stuck on using some sort of loop to single out each digit of the integer and print its word, then repeat for the next digit, and the next. 我坚持使用某种循环来选择整数的每个数字并打印其单词,然后对下一个数字和下一个重复。 I am fairly new at all this so any help would be appreciated! 我在这方面还算是新手,所以我们将不胜感激! Thanks. 谢谢。

Here's what I have so far (Not much, but I'm stuck on where to go with a loop): 到目前为止,这是我所拥有的(虽然不多,但是我仍然想循环使用):

#include <stdio.h>

int main(void)
{
        int num;

        printf("Please enter an integer: \n");
        scanf("%d", & num);

        while (num==0)
        {
        switch (num)
        {
                case (0):
                        printf("Zero ");
                        break;
                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 ");
                case (8):
                        printf("Eight ");
                        break;
                case (9):
                        printf("Nine ");
                        break;
                case (10):
                        printf("Ten ");
                        break;

        }
        }
        return 0;

}

so you can try reading a string with fgets and looping until the end of the string (or like in my example code, until the end of digits) and print names of digits. 因此,您可以尝试使用fgets读取字符串并循环直到字符串的末尾(或者像我的示例代码一样,直到数字的末尾)并打印数字的名称。

#include <stdio.h>

char *names[10] = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", };
int main()
{
    char buffer[500] = {0};
    int i = 0;
    fgets(buffer, sizeof(buffer), stdin);
    while (isdigit(buffer[i]))
        printf("%s ", names[buffer[i++] - '0']);

    return 0;
}

http://ideone.com/Ba7Rs3 http://ideone.com/Ba7Rs3

The easiest way to do this is to consume the digits from the right-hand side using integer division "/" & "%". 最简单的方法是使用整数除法“ /”和“%”从右侧使用数字。

Here's some partial code: 这是一些部分代码:

int digit;
//start a loop
//if num > 10
digit = num % 10;
num = num / 10;
//else
digit = num;
//break the loop

That will print the numbers from right to left. 这样将从右至左打印数字。 If you want left to right, you could make a recursive function that if num > 10, calls itself with the parameter of num / 10, and then prints the digit value. 如果要从左到右,则可以创建一个递归函数,如果num> 10,则使用num / 10参数进行调用,然后输出数字值。

Edit: Here's an example of your recursive function: 编辑:这是您的递归函数的示例:

void convertToWords (int num){
    if (num > 10){
        convertToWords(num / 10);
    int digit = num % 10;
    //your switch statement to print the words goes here
}

One possible approach: 一种可能的方法:

#include <stdio.h>

char *digits[10] = {
  "Zero", "One", "Two", "Three", "Four",
  "Five", "Six", "Seven", "Eight", "Nine"
};

int main() {
  int num, digit; 
  long long tenth = 1;
  printf("Please enter an integer: \n");
  scanf("%d", &num);

  while (tenth < num) {
    tenth *= 10;
  }

  while (tenth > 1) {
    tenth /= 10;
    digit = num / tenth;
    num %= tenth;
    printf("%s ", digits[digit]);
  }
  return 0;
}

Demo . 演示 Now for explanations: 现在进行解释:

First and foremost, it makes little sense to use switch here: digits are pretty darn linear by their nature, therefore their names can (and should) be stored in an array of strings instead ( char *digits[10] in this code). 首先,在这里使用switch几乎没有意义:由于数字的本质,数字是线性的,因此它们的名称可以(并且应该)存储在字符串数组中(此代码中的char *digits[10] )。 Then you'll be able to get a label for a particular digit just by accessing this array using this digit as an index. 然后,只需使用该数字作为索引访问此数组,就可以获取特定数字的标签。

Second, the key problem of this program is extracting each digit from the input separately. 其次,该程序的关键问题是从输入中分别提取每个数字。 It's easier to do going from right to left (take the result of number % 10 , assign number / 10 to number , repeat), but here things should be done in another way - left to right. 从右向左移动比较容易(将number % 10的结果,将number / 10分配给number ,重复),但是这里应该以另一种方式完成-从左到右。 So this is what we do: 这就是我们要做的:

  • calculate tenth - the first power of 10 that's bigger than the given number (for example, if we work with 546, that'll be 1000) 计算tenth -大于给定数字的10的第一个乘方(例如,如果我们使用546,则为1000)
  • at each subsequent iteration: 在每个后续迭代中:

-- divide tenth by 10 - tenth除以10

-- process the result of integer division of number by tenth -处理number的整数除以tenth

-- assign back to number the remainder of number divided by tenth -分配回number的余number除以tenth

At the first iteration tenth becomes 100 (1000/10), 546/100 gives you 5 (an integer divided by integer is integer, decimals are truncated), 546 % 100 gives you 46 - that's stored as a number for the second iteration. 在第一次迭代中, tenth变为100(1000/10),546/100给您5(整数除以整数就是整数,十进制被截断),546%100给您46-作为数字存储在第二次迭代中。

At the second iteration tenth becomes 10 (100/10), 46/10 gives you 4, 46 % 10 gives you 6. Next cycle: 10/10 => 1, 6/1 => 6, 6%1 => 0. So tenth has become equal to 1, and loop is stopped - as all the digits are processed. 在第二次迭代中, tenth变为10(100/10),46/10给您4,46%10给您6。下一个周期:10/10 => 1,6/1 => 6,6%1 => 0 。所以tenth等于1,并且循环停止-因为处理了所有数字。

The most understandable way IMO (if not the most efficient) uses powers of ten. IMO(如果不是最有效的话)使用十次幂的最容易理解的方式。 If we start with the number 543210 , then the number of digits is given by log10(543210) + 1 = 6. Then 如果我们以数字543210 ,则位数由log10(543210) + 1 = 6给出。

// start with a number
int num = 543210;
// how many digits?
int digits = log10(num) + 1; // 6
// now loop through each digit
for (int i = digits - 1; i > 0; --i) {
  int p = (int)pow(10, i);
  int digit = (num / p) % 10; // we want integer division
  switch (digit) { ... }
}

(Remember to #include <math.h> .) (请记住#include <math.h> 。)

A no limit solution inspired by @Hayri Uğur Koltuk 一个不受限制的解决方案,灵感来自@HayriUğurKoltuk

#include <ctype.h>
#include <stdio.h>
int main() {
  int ch;
  while (((ch = getc(stdin)) != EOF) && (isdigit(ch))) {
    static const char *Digit[10] = { "Zero", "One", "Two", "Three", "Four",
        "Five", "Six", "Seven", "Eight", "Nine" };
    printf("%s ", Digit[ch - '0']);
  }
  puts("\n");
  return 0;
}

A simple recursive solution 一个简单的递归解决方案

static void PrintDigit(unsigned n) {
  static const char *Digits[10] = {
    "Zero", "One", "Two", "Three", "Four",
    "Five", "Six", "Seven", "Eight", "Nine" };
  if (n > 9) {
    PrintDigit(n/10);
  }
  printf("%s ", Digits[n%10]);
}

void PrintDigits(unsigned n) {
  PrintDigit(n);
  printf("\n");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM