菜鸟问题,请问如何使结构指针数组,实现按平均成绩排序,先谢谢了

devotion 2007-10-21 01:16:17
#include <stdio.h>
#define N 50

struct student
{
int num;
char name[10];
float score1;
float score2;
float score3;
float ave;//平均成绩
};
void input(struct student *p);//输入函数
void display(struct student *p);//显示函数
void taxis(struct student *p);//排序函数

void main()
{
struct student a[N];
input(a);
printf("\n排序前的成绩\n");
display(a);

taxis(a);
printf("\n排序后的成绩\n");
display(a);
}

void input(struct student *p)//输入函数
{
char ch[1];

do
{
printf("输入学号:");
scanf("%d",&p->num);

printf("输入姓名:");
scanf("%s",&p->name);

printf("\n三门成绩:\n");
printf("输入成绩1:");
scanf("%f",&p->score1);

printf("输入成绩2:");
scanf("%f",&p->score2);

printf("输入成绩3:");
scanf("%f",&p->score3);

p->ave=(p->score1+p->score2+p->score3)/3;//平均分

p++;//移动指针

printf("\n是否继续(y/n):");
scanf("%s",&ch);
if(ch[0]=='n' || ch[0]=='N')
{
break;
}
}while(1);
p->num=0;
}
void display(struct student *p)//显示函数
{
int i,j,count=0;
for(i=0;i<N;i++)//查找结构数组的实际长度
{
if(p->num!=0)
{
count++;//保存数组的实际长度值
p++;
}
else
{
break;
}
}
p=p-count;//使指针回到结构数组的首位置
printf("学号\t姓名\t平均成绩\n");
for(j=0;j<count;j++)//循环打印详细信息
{
printf("%d\t%s\t%7.2f\n",p->num,p->name,p->ave);
p++;
}
}

void taxis(struct student *p)//排序函数
{
struct student *b;

int i,j,count=0;
for(i=0;i<N;i++)//查找结构数组的实际长度
{
if(p->num!=0)
{
count++;//保存数组的实际长度值
p++;
}
else
{
break;
}
}
for(i=0;i<count;i++)
{
p=p-count;//使指针回到结构数组的首位置
for(j=0;j<count-i-1;j++)
{
if(p->ave < (p+1)->ave)
{
b=p;
p=(p+1);
(p+1)=b;
}
p++;
}
}
}
不知道为什么?排序函数中始终有错,我的办法已经用尽了。望各位高手指点,谢谢
...全文
166 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
devotion 2007-10-22
  • 打赏
  • 举报
回复
问题搞定了,非常感谢各位。
devotion 2007-10-21
  • 打赏
  • 举报
回复
1楼,2楼的方法都用了,编译器能通过了,但是还是不能排序,全部照原样输出

我晕............
huiyamin428 2007-10-21
  • 打赏
  • 举报
回复
二楼的分析的比较的透彻,谢谢.
xzcanle 2007-10-21
  • 打赏
  • 举报
回复
在学习一下数据结构就可以很快的解决了
oo_v_oo 2007-10-21
  • 打赏
  • 举报
回复
1楼的排序错了
devotion 2007-10-21
  • 打赏
  • 举报
回复
谢谢
oo_v_oo 2007-10-21
  • 打赏
  • 举报
回复
看到有以下几个问题
1。既然使用的是结构数组,就不要采用指针形式访问数组资源,如果处理不当,容易造成指针错位
2。进行排序时,应该对数组中的数据进行交换,lZ所用的指针赋值不能达到目的
对排序函数修改,供LZ参考

void taxis(struct student *p)//排序函数
{
struct student b;

int i,j,count;
for(i=0;i<N;i++)//查找结构数组的实际长度
{
if(p[i].num==0) break;
}

count = i;
for(i=0;i <count-1;i++)
{
for(j=i+1;j <count;j++)
{
if(p[i].ave <p[j].ave)
{
b=p[i];
p[i]=p[j];
p[j]=b;
}
}
}
}
星羽 2007-10-21
  • 打赏
  • 举报
回复


void taxis(struct student *p)//排序函数
{
struct student b;

int i,j,count=0;
for(i=0;i <N;i++)//查找结构数组的实际长度
{
if(p->num!=0)
{
count++;//保存数组的实际长度值
p++;
}
else
{
break;
}
}


p -= count;
for(i = 0; i < count; i++)
{
for (j = i + 1; j < count; j++)
if (p[i].ave > p[j].ave)
{
b = p[i];
p[i] = p[j];
p[j] = b;
}
}
}


33,319

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧