【PAT】B1002 写出这个数

时间:2022-01-14 09:53:27

思路:

1.以字符串形式输入数据,计算结果

2.使用sprintf将结果数字转换为字符串(将数字每一位分开)

3.分别输出字符每一位

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


#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结构

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