c - 使用 if 和 switch 语句在 C 中练习:编写代码将 2 位数字转换为单词
问题描述
我正试图弄清楚这个练习。作业要求用单词转换两位数,输出应该是这样的:
Enter a two-digit number:45
You entered the number forty-five.
我仍然是编程的初学者。我在这本 C 编程书籍的这一章,在关于switch
andif
语句的练习部分。该练习建议使用两种switch
语句,一种用于十位,另一种用于单位,但其中的数字11
需要19
特殊处理。
问题是我试图弄清楚我应该为 和 之间的数字做什么11
,19
我正在考虑使用该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;
解决方案
这对学习者来说是一个很好的问题,不想放弃太多
// 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”。
推荐阅读
- reporting-services - 基于文本框或列的可见性的 SSRS 表达式
- java - 不理解方法返回的问题
- r - 为矩阵中的某些列查找唯一行,并保留剩余列的值
- java - 如何在 ReactiveMongoRepository 中插入更新查询
- c - 传递数组时在C中的函数参数中强制数组大小
- java - 运行junit测试时Rest API日期参数更改
- php - 致命错误:未捕获的 ArgumentCountError:函数 App\Models\Model 的参数太少
- vb.net - 异常访问冲突 (msvcrt.dll)
- node.js - 如何在亚马逊 AWS 中将 lex 与 lambda 集成?
- puppeteer - 在 puppeteer 中执行多个 DOM 操作是否会导致任何问题?