题目
读入一个正整数 n
,计算其各位数字之和,用汉语拼音写出和的每一位数字。
输入格式:
每个测试输入包含 1 个测试用例,即给出自然数 n
的值。这里保证 n
小于 10100。
输出格式:
在一行内输出 n 的各位数字之和的每一位,拼音数字间有 1 空格,但一行中最后一个拼音数字后没有空格。
输入样例:
1234567890987654321123456789
输出样例:
yi san wu
答案
#include <stdio.h>
int main(int argc, char* argv[])
{
char spell[10][10] = {"ling","yi","er","san","si","wu","liu","qi","ba","jiu"};//I almost forget the zero spell contain 'g' or not... sougouPinyin save me
int n;
int sum = 0;
char c;
int temp;
int i = 0; //circle variale
char conv_spells[10];
while((c = getc(stdin)) != '\n')//the first bug come from I ignore the priority of operator
{
sum += c - '0';
}
//printf("%d",sum);
temp = sum;
// I believe some better ways waiting me to figure out
/*
while(temp/10>=1)
{
temp /=10;
}
printf("%s",spell[temp]);
*/
while(temp>0)
{
conv_spells[i++] = temp%10;
temp /= 10;
}
printf("%s",spell[conv_spells[--i]]);
for(i--;i>=0;i--)
{
printf(" ");
printf("%s",spell[conv_spells[i]]);
}
return 0;
}
过程
字符串的应用,还不是很熟悉,取一个数的各位,从最高位依次开始,还有没有更好的方法,等我百度一下。
答案二
(update on 2020-4-2 and cover 2020-4-1)
#include <stdio.h>
int main(int argc, char* argv[])
{
char spell[10][10] = {"ling","yi","er","san","si","wu","liu","qi","ba","jiu"};//I almost forget the zero spell contain 'g' or not... sougouPinyin save me
int sum = 0;
int i = 0; //circle variale
//update this block
char numb[101];
char s[4];
gets(numb);// gets rather than getc
while(numb[i]!='\0')
{
sum += numb[i++] - '0';
}
sprintf(s, "%d", sum); // sprintf(char *buffer, const char *format,[ argument]) change any types of data to string,result save in buffer
//using the sprintf_s function and compile fail ,then the unsafe version sprintf() comes.
for (i = 0; s[i] != 0; i++) {
if (i > 0) //消除第一个空格
printf(" ");
printf("%s",spell[s[i] - '0']);
}
return 0;
//update end
}
总结
在找其他答案的时候,还遇到类似switch输出的,还有这个,很佩服就是了,简单明了啥子复杂逻辑不用
char pin[10][10]={"ling","yi","er","san","si","wu","liu","qi","ba","jiu"};
if(j>99)
{
printf("%s ",pin[j/100]);
printf("%s ",pin[j%100/10]);
printf("%s",pin[j%100%10]);
}else if(j>9)
{
printf("%s ",pin[j/10]);
printf("%s",pin[j%10]);
}else{
printf("%s",pin[j]);
}
整体分两块,一个是处理输入求和,这个问题不大。在c语言里面,处理字符串是需要加强练习的~