7-2 又见A+B 分数 15 作者 黄龙军 单位 绍兴文理学院 某天,诺诺在做两个10以内(包含10)的加法运算时,感觉太简单。于是她想增加一点难度,同时也巩固一下英文(学好英文真的很重要!),就把数字用英文单词表示。为了验证她的答案,请根据给出的两个英文单词表示的数字,计算它们之和并以英文单词的形式输出。如果没记住这些数字的英文单词,那就先好好学学英文吧。 输入格式: 多组测试数据,处理到文件尾。每组测试输入两个英文单词表示的数字A、B(0≤A,B≤10)。 输出格式: 对于每组测试,在一行上输出A+B的结果,要求以英文单词表示。 输入样例: ten ten one two 输出样例: twenty three
时间: 2024-02-11 09:08:02 浏览: 33
以下是一种可能的实现方式:
```c
#include <stdio.h>
#include <string.h>
const char *digit_1_to_19[] = {
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"
};
const char *digit_20_to_90[] = {
"", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"
};
int parse(const char *word) {
for (int i = 0; i < 20; i++) {
if (strcmp(word, digit_1_to_19[i]) == 0) {
return i;
}
}
for (int i = 2; i < 10; i++) {
char buf[16];
snprintf(buf, sizeof(buf), "%s%d", digit_20_to_90[i], 0);
if (strcmp(word, buf) == 0) {
return i * 10;
}
}
return -1;
}
void print(int num) {
if (num >= 20) {
printf("%s", digit_20_to_90[num / 10]);
if (num % 10 != 0) {
printf(" %s", digit_1_to_19[num % 10]);
}
} else {
printf("%s", digit_1_to_19[num]);
}
}
int main() {
char a[16], b[16];
while (scanf("%s%s", a, b) == 2) {
int x = parse(a);
int y = parse(b);
int z = x + y;
print(z);
printf("\n");
}
return 0;
}
```
首先定义两个字符串数组 `digit_1_to_19` 和 `digit_20_to_90`,分别用于存储数字 0 到 19 和 20 到 90 的英文单词表示。在 `parse` 函数中,首先遍历 `digit_1_to_19` 数组,查找与输入单词相同的数字,如果找到则返回对应数字。如果找不到,则遍历 `digit_20_to_90` 数组,将输入单词和数组中的每个单词组合起来,形成 20 到 90 中的每个数,并查找与输入单词相同的数字。如果还是找不到,则返回 -1 表示解析失败。在 `print` 函数中,首先判断数字是否大于等于 20,如果是,则输出 20 到 90 中的十位数对应的英文单词,如果个位数不为 0,则再输出个位数对应的英文单词。如果数字小于 20,则直接输出对应的英文单词。在 `main` 函数中,读入两个英文单词,解析出对应的数字,计算它们的和,并将和的数字转换成英文单词输出。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)