3.9 KiB
3.9 KiB
C 程序:使用单词打印两位数
原文:https://overiq.com/c-examples/c-program-to-print-the-two-digit-number-in-words/
最后更新于 2020 年 7 月 27 日
下面是一个用单词打印两位数的 C 程序:
/***********************************************
Program to print the two digit number in words
***********************************************/
#include <stdio.h> // include stdio.h library
int main(void)
{
int num1, num2;
printf("Enter a two-digit number: ");
scanf("%1d%1d", &num1, &num2);
printf("You have entered: ");
// print word for the first digit
switch (num1)
{
case 1:
// special case for numbers between 11-19
switch (num2)
{
case 0:
printf("ten");
return 0;
case 1:
printf("eleven");
return 0;
case 2:
printf("twelve");
return 0;
case 3:
printf("thirteen");
return 0;
case 4:
printf("fourteen");
return 0;
case 5:
printf("fifteen");
return 0;
case 6:
printf("sixteen");
return 0;
case 7:
printf("seventeen");
return 0;
case 8:
printf("eigthteen");
return 0;
case 9:
printf("nineteen");
return 0;
}
case 2:
printf("twenty");
break;
case 3:
printf("thirty");
break;
case 4:
printf("forty");
break;
case 5:
printf("fifty");
break;
case 6:
printf("sixty");
break;
case 7:
printf("seventy");
break;
case 8:
printf("eighty");
break;
case 9:
printf("ninety");
break;
}
// print word for the second digit
switch (num2)
{
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;
}
预期输出:
第一次运行:
Enter a two-digit number: 19
You have entered: nineteen
第二次运行:
Enter a two-digit number: 95
You have entered: ninety-five
它是如何工作的
该程序由两个外部switch语句组成。第一个定义在第 17-78 行,第二个定义在第 81-110 行。第一个 switch 语句打印第一个数字的单词,第二个 switch 语句打印第二个数字的单词。从 11 到 19 的数字需要特殊处理,并由第 21-53 行中定义的嵌套 switch 语句处理。
推荐阅读