题目详情
读入一个正整数 n,计算其各位数字之和,用汉语拼音写出和的每一位数字。
输入格式: 每个测试输入包含 1 个测试用例,即给出自然数 n 的值。这里保证 n 小于 10 的100次方。
输出格式: 在一行内输出 n 的各位数字之和的每一位,拼音数字间有 1 空格,但一行中最后一个拼音数字后没有空格。
输入样例: 1234567890987654321123456789 输出样例: yi san wu
错漏
开始时未给字符串预留 ‘\0’ 导致溢出 后发现输入赋值判断条件似乎仍有问题 报错代码部分如下:
char a[101];
for (i = 0; cin.get() != '\n'; i++)
{
cin >> a;
}
int div,ten,hun,tho;
for(i=0;i<=100&&a[i]!=0;i++)
{
sum+=a[i]-48;
}
猜测原因为cin输入与判断条件cin.get矛盾(不确定) 换用getchar进行判断赋值
代码与优化
弟弟思路(我的):
#include<iostream>
using namespace std;
int main()
{
int i = 0, sum = 0;
char a[101];
while((n=getchar())!='\n')
{
sum+=n-48;
}
int div, ten, hun, tho;
div = sum % 10;
sum /= 10;
ten = sum % 10;
sum /= 10;
hun = sum % 10;
sum /= 10;
tho = sum % 10;
switch (tho)
{
case 0:break;
case 1:cout << "yi "; break;
case 2:cout << "er "; break;
case 3:cout << "san "; break;
case 4:cout << "si "; break;
case 5:cout << "wu "; break;
case 6:cout << "liu "; break;
case 7:cout << "qi "; break;
case 8:cout << "ba "; break;
case 9:cout << "jiu "; break;
}
switch (hun)
{
case 0:
if (tho == 0)
tho = 0;
else
cout << "ling ";
break;
case 1:cout << "yi "; break;
case 2:cout << "er "; break;
case 3:cout << "san "; break;
case 4:cout << "si "; break;
case 5:cout << "wu "; break;
case 6:cout << "liu "; break;
case 7:cout << "qi "; break;
case 8:cout << "ba "; break;
case 9:cout << "jiu "; break;
}
switch (ten)
{
case 0:
if (tho == 0 && hun == 0)
tho = 0;
else
cout << "ling ";
break;
case 1:cout << "yi "; break;
case 2:cout << "er "; break;
case 3:cout << "san "; break;
case 4:cout << "si "; break;
case 5:cout << "wu "; break;
case 6:cout << "liu "; break;
case 7:cout << "qi "; break;
case 8:cout << "ba "; break;
case 9:cout << "jiu "; break;
}
switch (div)
{
case 0:
cout << "ling ";
break;
case 1:cout << "yi "; break;
case 2:cout << "er "; break;
case 3:cout << "san "; break;
case 4:cout << "si "; break;
case 5:cout << "wu "; break;
case 6:cout << "liu "; break;
case 7:cout << "qi "; break;
case 8:cout << "ba "; break;
case 9:cout << "jiu "; break;
}
return 0;
}
优化后(大佬思路): 使用字符串或二维数组表示拼音 利用c语言中printf特性,进行对应输出 (看来printf的输出相较cout确实更好用)
#include<stdio.h>
int main()
{
char py[][9] = { "ling","yi","er","san","si","wu","liu","qi","ba","jiu" };
char n;
int sum = 0;
while ((n = getchar()) != '\n')
{
sum += n - 48;
}
int a[100], t = 0;
while (sum)
{
a[t] = sum % 10;
sum /= 10;
t++;
}
for (; t != 0; t--)
{
printf("%s", py[a[t - 1]]);
if (t != 1)printf(" ");
}
}
|