首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

大一新生,

2012-02-25 
大一新生,紧急求助!!题目要求:输入5个国家名称,并按升序排列。#include stdio.h#include string.hint m

大一新生,紧急求助!!
题目要求:输入5个国家名称,并按升序排列。

#include <stdio.h>
#include <string.h>
int main()
{
char str1[50],str2[50],str3[50],str4[50],str5[50],*p1,*p2,*p3,*p4,*p5,*tp;
int i,t=0;
printf("请输入五个国家的名称,本程序将把他们的名字按升序排列:");

  gets(str1);//输入字符串
gets(str2);
gets(str3);
gets(str4);
gets(str5);

  p1=str1;//指针指向字符串
p2=str2;
p3=str3;
p4=str4;
p5=str5;

  for (i=0;i<50;i++)
{
if (strcmp(p1,p2)>0)//用函数比较字符串的大小,然后交换指针变量
{
tp=p2;
p2=p1;
p1=tp;
}
if (strcmp(p2,p3)>0)
{
tp=p3;
p3=p2;
p2=tp;
}
if (strcmp(p3,p4)>0)
{
tp=p4;
p4=p3;
p3=tp;
}
if (strcmp(p4,p5)>0)
{
tp=p5;
p5=p4;
p4=tp;
}
}

printf("\n\n国家名按升序排列为:\n\n");
puts(p1);

printf("\n");
puts(p2);

printf("\n");
puts(p3);

printf("\n");
puts(p4);

printf("\n");
puts(p5);

printf("\n");
return 0;
}





这个是我写的程序,但我觉得太麻烦,有没有什么方法能简便一点,但要求用指针完成??
求助啊!!

[解决办法]
你可以定义一个char* pa[5],每个里边存的都是指针
int i=0
int m存放最小的那个串的指针在pa里边的下标
for(;i<5;i++)
每次从第i个开始,选出最小的那个串来跟第一个交换。for完了就排序完了

我感觉这是最好想的排序方法


[解决办法]

C/C++ code
#include <stdio.h>#include <string.h>int main(){    char str[5][50], *p[5], *pt;    int i, j, t=0;    printf("请输入五个国家的名称,本程序将把他们的名字按升序排列:");    for(i=0; i < 5; i++)    {        gets(str[i]);//输入字符串        p[i] = str[i];    }        for(j=4; j >=0 ;j--) //冒泡排序    {        for(i=0; i < j; i++)        {            if (strcmp(p[i],p[i+1])>0)//用函数比较字符串的大小,然后交换指针变量            {                pt = p[i];                p[i] = p[i+1];                p[i+1] = pt;            }        }    }    printf("\n\n国家名按升序排列为:\n\n");    for(i=0; i < 5; i++)    {       printf("%s\n",p[i]);    }    return 0;} 

热点排行