C语言学习八结构体,综合应用,学生管理系统

实现功能的代码:

# include <stdio.h>
# include <malloc.h>

struct Student
{
	int age;
	float score;
	char name[100];
};


int main(void)
{
	int len;
	struct Student * pArr;
	int i, j;
	struct Student t;

	// 动态的构造一维数组
	printf("请输入学生的个数:\n");
	printf("len = ");
	scanf("%d", &len);
	pArr = (struct Student *)malloc(len * sizeof(struct Student));

	for (i=0; i<len; i++)
	{
		printf("请输入第%d个学生的信息:\n", i+1);
		printf("name = ");
		scanf("%s", pArr[i].name);	//name是数组名,本身就已经是数组首元素的地址,所以pArr[i].name不能够改为&pArr[i].name

		printf("age = ");
		scanf("%d", &pArr[i].age);

		printf("score = ");
		scanf("%f", &pArr[i].score);
	}

	for (i=0; i<len-1; i++)
	{
		for (j=0; j<len-1-i; j++)
		{
			if (pArr[j].score > pArr[j+1].score)	//大于是升序,小于是降序
			{
				t = pArr[j];
				pArr[j] = pArr[j+1];
				pArr[j+1] = t;
			}
		}
	}

	printf("\n\n学生的信息是:\n");
	//输出
	for (i=0; i<len; i++)
	{
		printf("第%d个学生的信息是:\n", i+1);
		printf("name = %s\n", pArr[i].name);
		printf("age = %d\n", pArr[i].age);
		printf("score = %f\n", pArr[i].score);
		printf("\n");
	}
	

	return 0;
}

 

调优实现的代码如下:

/*
	2013年3月15日22:07:07
	实现学生管理系统功能,其实就是实现用户输入几个学生的信息,然后将成绩从高到低排序一下,显示一下
	用了结构体,函数,指针,动态分配
*/
# include <stdio.h>
# include <malloc.h>

struct Student
{
	int age;
	float score;
	char name[100];
};
void sort(struct Student *, int);
void InputStudent(struct Student *, int);
void OutputStudent(struct Student *, int);

int main(void)
{
	int len;
	struct Student * pArr;
	// 动态的构造一维数组
	printf("请输入学生的个数:\n");
	printf("len = ");
	scanf("%d", &len);
	pArr = (struct Student *)malloc(len * sizeof(struct Student));
	
	InputStudent(pArr, len);
	sort(pArr, len);
	OutputStudent(pArr, len);

	return 0;
}

void InputStudent(struct Student * pArr, int len)
{
	int i;

	for (i=0; i<len; i++)
	{
		printf("请输入第%d个学生的信息:\n", i+1);
		printf("name = ");
		scanf("%s", pArr[i].name);	//name是数组名,本身就已经是数组首元素的地址,所以pArr[i].name不能够改为&pArr[i].name

		printf("age = ");
		scanf("%d", &pArr[i].age);

		printf("score = ");
		scanf("%f", &pArr[i].score);
	}
}

void OutputStudent(struct Student * st, int len)
{
	int i;
	printf("\n\n学生的信息是:\n");
	//输出
	for (i=0; i<len; i++)
	{
		printf("第%d个学生的信息是:\n", i+1);
		printf("name = %s\n", st[i].name);
		printf("age = %d\n", st[i].age);
		printf("score = %f\n", st[i].score);
		printf("\n");
	}
}

void sort(struct Student * pArr, int len)
{
	int i, j;
	struct Student t;
	for (i=0; i<len-1; i++)
	{
		for (j=0; j<len-1-i; j++)
		{
			if (pArr[j].score > pArr[j+1].score)	//大于是升序,小于是降序
			{
				t = pArr[j];
				pArr[j] = pArr[j+1];
				pArr[j+1] = t;
			}
		}
	}	
}

 

你可能感兴趣的:(C语言)