在主函数输入10个等长的字符串。用另一函数对它们排序。然后在主函数输出这10个已经排好序的字符串。

2016-06-19 16:44:07  分类: c程序设计第四版谭浩强课后答案  参与:

 在主函数输入10个等长的字符串。用另一函数对它们排序。然后在主函数输出这10个已经排好序的字符串。

c程序设计第四版谭浩强课后答案

以下是此题的【c源代码】,需要【c++源代码】请点击进入

方法1:用字符型二维数组的
【c源程序】
#include <stdio.h>
#include <string.h>
int main()
{void sort(char s[][6]);
 int i;
 char str[10][6];
 printf("input 10 strings:\n");
 for (i=0;i<10;i++)
   scanf("%s",str[i]);
 sort(str);
 printf("Now,the sequence is:\n");
 for (i=0;i<10;i++)
   printf("%s\n",str[i]);
 return 0;
}

void sort(char s[10][6])
{int i,j;
 char *p,temp[10];
 p=temp;
 for (i=0;i<9;i++)
   for (j=0;j<9-i;j++)
     if (strcmp(s[j],s[j+1])>0)
      {strcpy(p,s[j]);
       strcpy(s[j],s[+j+1]);
       strcpy(s[j+1],p);
      }
}


方法2:用指向一维数组的指针作函数参数
【c源程序】
#include <stdio.h>
#include <string.h>
int main()
{void sort(char (*p)[6]);
 int i;
 char str[10][6];
 char (*p)[6];
 printf("input 10 strings:\n");
 for (i=0;i<10;i++)
   scanf("%s",str[i]);
 p=str;
 sort(p);
 printf("Now,the sequence is:\n");
 for (i=0;i<10;i++)
   printf("%s\n",str[i]);
 return 0;
 }

void sort(char (*s)[6])
{int i,j;
 char temp[6],*t=temp;
 for (i=0;i<9;i++)
   for (j=0;j<9-i;j++)
     if (strcmp(s[j],s[j+1])>0)
      {strcpy(t,s[j]);
       strcpy(s[j],s[+j+1]);
       strcpy(s[j+1],t);
      }
}

 

来源:c程序设计第四版谭浩强课后答案

本文链接:http://www.wb98.com/c/post/tanhaoqiang_8.11.html

本站文章搜索:

<< 上一篇下一篇 >>

搜索

网站分类

Tags列表

赞助商链接