【pat】b1002 写出这个数

思路:
1.以字符串形式输入数据,计算结果
2.使用sprintf将结果数字转换为字符串(将数字每一位分开)
3.分别输出字符每一位

1,笨方法,用的ifelse来判断输出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43

#include<stdio.h>
#include<string.h>
char arr[110];

int getsum() {
int sum = 0;
int len = strlen(arr);
for (int i = 0; i<len; i++) {
sum += arr[i] - '0';
}
return sum;
}
int main() {
scanf("%s", arr);
int sum = getsum();
sprintf(arr, "%d", sum);
int len = strlen(arr);
for (int i = 0; i<len; i++) {
if (i != 0) printf(" ");
if (arr[i] == '1')
printf("yi");
else if (arr[i] == '2')
printf("er");
else if (arr[i] == '3')
printf("san");
else if (arr[i] == '4')
printf("si");
else if (arr[i] == '5')
printf("wu");
else if (arr[i] == '6')
printf("liu");
else if (arr[i] == '7')
printf("qi");
else if (arr[i] == '8')
printf("ba");
else if (arr[i] == '9')
printf("jiu");
else if (arr[i] == '0')
printf("ling");
}
return 0;
}

2,简化代码,用如下代码简化输出部分的ifelse结构

1
2
char data[10][20] = { "ling","yi","er","san","si","wu","liu","qi","ba","jiu" };
printf("%s", data[arr[i] - '0']);