首页 > 解决方案 > 使用 if 和 switch 语句在 C 中练习:编写代码将 2 位数字转换为单词

问题描述

我正试图弄清楚这个练习。作业要求用单词转换两位数,输出应该是这样的:

Enter a two-digit number:45
You entered the number forty-five.

我仍然是编程的初学者。我在这本 C 编程书籍的这一章,在关于switchandif语句的练习部分。该练习建议使用两种switch语句,一种用于十位,另一种用于单位,但其中的数字11需要19特殊处理。

问题是我试图弄清楚我应该为 和 之间的数字做什么1119我正在考虑使用该if语句,但是第二个switch函数将包含在输出中,它会变成类似You've entered the number eleven one.

这是迄今为止我一直在写的程序(不完整):

    int digits;

    printf("Enter a two-digit number:");

    scanf("%d", &digits);

    printf("You entered the number ");

    switch (digits / 10) {
    case 20:
        printf("twenty-");break;
    case 30:
        printf("thirty-");break;
    case 40:
        printf("forty-");break;
    case 50:
        printf("fifty-");break;
    case 60:
        printf("sixty-");break;
    case 70:
        printf("seventy-");break;
    case 80:
        printf("eighty-");break;
    case 90:
        printf("ninety-");break;
    }

    switch (digits % 10) {
    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;
    }
    return 0;

标签: cif-statementswitch-statement

解决方案


这对学习者来说是一个很好的问题,不想放弃太多

// Pseudo code
int print_two_digits(int tens, int ones) {
  if (tens 2 or more) 
    print tens_place(tens) // use `tens` to index an array of strings.
    if (ones == 0) return;
    print -
  else 
    ones += tens*10;

  print ones_text(ones) // ones is 0-19 at this point. Index an string array with `ones`
}

如何索引字符串数组并打印?

// index: valid for 0,1,2
void print rgb(int index) {
  const char *primary[] = { "red", "green", "blue" };
  puts(primary[index]);
}

琐事:文本 10-99 中的英文数字大多是大端序,最重要的在前,如“四十二”,除了 [11-19] 中的小数字在前,如“四个teen”。


推荐阅读