将数字的每一位倒序存入数组,再正序输出,为什么这样是错误的?
问题如下:
输入格式:
输入在一行中给出一个整数,如:1234。
提示:整数包括负数、零和正数。
输出格式:
在一行中输出这个整数对应的拼音,每个数字的拼音之间用空格分开,行末没有最后的空格。
如
yi er san si。
我的思路是先用一个数组存储数字的每一位,是倒序存储。再用另一个数组按顺序存储拼音(a[0]=ling a[1]=er这样),最后索引。 比如667,存入数组的就是7,6,6
因为存储拼音的数组是按顺序的,所以只要索引a[6]就可以
#include
int main(void)
{
int n=0;
int count = 0, i = 0;
scanf("%d", &n);
char a[10] = { 'ling','ling','er','san','si','wu','liu','qi','ba','jiu'};
int b[100] = { 0 };
if (n < 0)
{
printf("fu ");
n = -n;
}
while (n != 0)
{
b[i] = n % 10;
count++;
i++;
n /= 10;
}
printf("%d",count);
for (int i = count - 1; i >= 0; i--)
{
printf("%d", a[b[i]]);
if (i != 0)
printf(" ");
}
}
好像最后一个for循环部分是错的,有时候这样写还会栈溢出,这部分不太懂,求指点QAQ
在网上看到了一个C++的解法 为什么C++这样写for循环就是对的呀
#include
#include
using namespace std;
int main(){
string a[10]={"ling","yi","er","san","si","wu","liu","qi","ba","jiu"};
int z;
int b[20];//存放整数的每位数字。
cin>>z;
int i=0;
int count=0;//记录整数的一共有都少位。
//分开讨论0.
if(z==0) cout<if(z<0) {
cout<<"fu ";
z=-z;
}
//循环用于存放整数的每个位。
while(z){
b[i]=z%10;
z=z/10;
count++;
i++;
}
//输出结果。
for(i=count-1;i>=0;i--){
cout<if(i!=0) cout<<" ";//注意最后并没有空格。
}
return 0;
}
题主代码修改如下,见注释,供参考:
#include <stdio.h>
int main(void)
{
int n=0;
int count = 0, i = 0;
scanf("%d", &n);
//char a[10] = { 'ling','ling','er','san','si','wu','liu','qi','ba','jiu'};
char* a[10] = {"ling","yi","er","san","si","wu","liu","qi","ba","jiu"}; //修改
int b[100] = { 0 };
if (n < 0)
{
printf("fu ");
n = -n;
}
while (n != 0)
{
b[i++] = n % 10;
//count++; 修改
//i++; 修改
n /= 10;
}
//printf("%d",count); 修改
for (i--; i >= 0; i--) //for (int i = count - 1; i >= 0; i--)修改
{
printf("%s", a[b[i]]);//printf("%d", a[b[i]]); 修改
if (i != 0)
printf(" ");
}
return 0;
}
再提供一个浓缩版的写法,供你参考:
#include <stdio.h>
int main()
{
int i;
char* num[10] = { "ling","yi","er","san","si","wu","liu","qi","ba","jiu" };
char c[100] = { 0 };
scanf("%s", c);
for (i = 0; c[i] != '\0'; i++)
printf(i == 0 && c[i] == '-' ? "fu" : i == 0 ? "%s" : " %s", num[c[i] - '0']);
return 0;
}
首先是要把数位数字的拼音定义为二维字符数组,因为一个拼音是一个字符串,10个字符串的话可以用二维字符数组存储;
然后打印结果时,打印数位的拼音要用%s, 因为数位数字的拼音是对应的字符串;
然后0对应的拼音要修改一下;
修改如下:
#include <stdio.h>
int main(void)
{
int n=0;
int count = 0, i = 0;
scanf("%d", &n);
char a[10][100] = { "ling","yi","er","san","si","wu","liu","qi","ba","jiu"} ;
int b[100] = { 0 };
if (n < 0)
{
printf("fu ");
n = -n;
}
while (n != 0)
{
b[i] = n % 10;
count++;
i++;
n /= 10;
}
// printf("%d\n",count);
for (int i = count-1; i >=0 ; i--)
{
printf("%s ", a[b[i]]);
if (i != 0)
printf(" ");
}
}