都是新手,交流下,下面是我写的,可以运行:
#include<stdio.h>
#include<malloc.h>
struct student
{
int age;
char name[100];
float score;
};
int main(void)
{
int len,i,j,k,n;
printf("请输入学生人数:");
scanf("%d", &len);
struct student * parr = (struct student *)malloc(sizeof(struct student)*len);
for(i = 0; i < len; i++)
{
printf("请输入第%d个学生的信息", i+1);
printf("age= ");
scanf("%d", &((parr+i)->age));
printf("name= ");
scanf("%s", &((parr+i)->name));
printf("score= ");
scanf("%f", &((parr+i)->score));
}
for(j = 0; j < len-1; j++)
{
for(k = 0; k < len-1-j; k++)
{
if((parr+k)->score < (parr+k+1)->score)
{
struct student t;
t = *(parr+k);
*(parr+k) = *(parr+k+1);
*(parr+k+1) = t;
}
}
}
for(n = 0;n < len; n++)
{
printf("以下是%s的成绩", (parr+n)->name);
printf("年龄是%d\n", (parr+n)->age);
printf("名字是%s\n", (parr+n)->name);
printf("分数是%f\n", (parr+n)->score);
}
return 0;
}
我还写了个函数的,功能扩充了一点点:
#include<stdio.h>
#include<malloc.h>
struct student
{
int ID;
char name[50];
int age;
float score;
};
void input(struct student **, int);
void output(struct student **, int);
void sort(struct student **, int);
int main(void)
{
int num;
printf("请输入学生个数:num =");
scanf("%d", &num);
struct student * pArra =(struct student *)malloc(num * sizeof(struct student));
input(&pArra, num);
sort(&pArra, num);
output(&pArra, num);
return 0;
}
void input(struct student ** pArra,int num)
{
int i;
for(i = 0; i < num; i++)
{
printf("请输入第%d个学生的信息:\n", i+1);
printf("学号");
scanf("%d", &((*pArra+i)->ID));
printf("姓名:\n");
scanf("%s", &((*pArra+i)->name));
printf("年龄:\n");
scanf("%d", &((*pArra+i)->age));
printf("分数:\n");
scanf("%f", &((*pArra+i)->score));
}
}
void output(struct student ** pArra,int num)
{
int ID,i,j;
char ch;
do
{
printf("按1查询全部,按0精确查询");
scanf("%d", &j);
if(j == 1)
{
for(i = 0; i < num; i++)
{
printf("学号: %d\n", (*pArra+i)->ID);
printf("姓名: %s\n", (*pArra+i)->name);
printf("年龄:%d\n", (*pArra+i)->age);
printf("分数: %f\n", (*pArra+i)->score);
printf("\n");
}
}
else if(j == 0)
{
printf("请输入要查询的学生学号:");
scanf("%d", &ID);
for(i = 0;i < num; i++)
{
if(ID == (*pArra+i)->ID)
{
printf("以下是该学生的信息:\n");
printf("学号: %d\n", (*pArra+i)->ID);
printf("姓名: %s\n", (*pArra+i)->name);
printf("年龄:%d\n", (*pArra+i)->age);
printf("分数: %f\n", (*pArra+i)->score);
}
}
}
else
printf("请输入 0 或 1 查询\n");
printf("是否要继续查询 Y/N\n");
scanf(" %c", &ch);
}while('Y' == ch||'y' == ch);
}
void sort(struct student ** pArra,int num)
{
int i,j;
float t;
for(i = 0; i < num-1; i++)
{
for(j=0; j < num-1-i; j++)
{
if(((*pArra+j)->score) < ((*pArra+j+1)->score))
{
t = (*pArra+j)->score;
(*pArra+j)->score = (*pArra+j+1)->score;
((*pArra+j+1)->score) = t;
}
}
}
}
希望对你有帮助