题目

答案
#include<stdio.h>
#include<string.h>
#include<math.h>
int main()
{
char str[30][30],t[30],temp[30];
int n=0,i,j,k;
while(1)
{
gets(temp);
if(strcmp(temp,"#")==0) break;
strcpy(str[n],temp);
n++;
}
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
int len1=strlen(str[i]),len2=strlen(str[j]);
if(len2<len1)
{
strcpy(t,str[i]);
strcpy(str[i],str[j]);
strcpy(str[j],t);
}
}
}
for(i=0;i<n;i++)
printf("%s ",str[i]);
}
问题总结
这道题我自己错将单词总数n多加了一个,导致结果异常
while(1)
{
gets(temp);
if(strcmp(temp,"#")==0) break;
strcpy(str[n],temp);
n++;
}
我之前就是在这组循环结束后又多写了一个n++;,但经过逻辑分析这句话是不能加的。
这篇博客讨论了一道C++编程题,涉及字符串排序。代码实现了一个程序,用于读取多行英文单词,然后按照单词长度升序排列。错误分析中提到,原本在读取单词的循环后面多加了一个不必要的n++,导致单词计数错误,修正后程序能正确排序并打印单词。
2万+

被折叠的 条评论
为什么被折叠?



