Structure Beginner

The first contact about the structure was compiled by myself according to the code listed in the case without studying after a laboratory assessment.

Topic:
2. Create an appropriate structure to store the specified data, and write the corresponding function to complete the specified operation.
(1) Deposit the following data in
sequence : Name, Student ID, Gender Order
Xiaoming 20201034 Male 1
Xiaohong 20201057 Female 5
Li Hua 20201042 Male 3

小明 20201034 男 1

Xiaohong 20201057 Male 3
Li Hua 20201042 Male 5
(2) Write the function ShowInfo to output all information.
(3) Write the function SortShow so that the stored data is output in descending order of student number (a sorting algorithm is required);

My code (a bit flawed):

#include <stdio.h>
struct stu
{
    
    
	char name[3];
	int number[3];
	char n[3];
	int x[3];
};
int main()
{
    
    
	int i,j;
	int num;
	struct stu st[3]={
    
    
		{
    
    "xiaoming",20201034,"man",1},
		{
    
    "xiaohong",20201057,"woman",5},
		{
    
    "lihua",20201042,"man",3}
	};
struct stu temp;
num=3;
for(i=0;i<num;i++)
{
    
    
for(j=0;j<num-i-1;j++)
{
    
     
	if(st[j].number[3]<st[j+1].number[3])
	{
    
    
		temp=st[j];
		st[j]=st[j+1];
		st[j+1]=temp;
	}
}
}
printf("姓名\t学号\t性别\t次序\n");
for(i=0;i<num;i++)
{
    
    
	printf("%s\t%d\t%s\t%d\n",
		st[i].name,st[i].number,st[i].n,st[i].x);
}
}

Operation result:
Insert picture description here
served. . . . . .

After correction:

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

typedef struct Stu
{
    
    
	char name[5];
	int id;
	char sex[1];
	int num;
}STU;

void init(STU *stu)
{
    
    
	int i;
	STU *s = stu;

	for(i=0;i<3;i++)
	{
    
    
		scanf("%s",s[i].name);
		scanf("%d",&s[i].id);
		scanf("%s",s[i].sex);
		scanf("%d",&s[i].num);
	}
}

void Show(STU *stu)
{
    
    
	int i;
	STU *s = stu;

	for(i=0;i<3;i++,s++)
	{
    
    
		printf("%s %d %s %d\n",s->name,s->id,s->sex,s->num);
	}
}

void SortShow(STU *stu)
{
    
    
	int i,j,flag,flagsort[3]={
    
    0,1,2};
	STU *s = stu;

	for(i=0;i<2;i++)
	{
    
    
		for(j=0;j<2-i;j++)
		{
    
    
			if(s[flagsort[j]].id < s[flagsort[j+1]].id)
			{
    
    
				flag = flagsort[j];
				flagsort[j]=flagsort[j+1] ;
				flagsort[j+1] = flag ;
			}
		}
	}

	for(i=0;i<3;i++)
	{
    
    
		printf("%s %d %s %d\n",s[flagsort[i]].name,s[flagsort[i]].id,s[flagsort[i]].sex,s[flagsort[i]].num);
	}
	
}

int main (void)
{
    
    
	STU s[3];
	printf("Please input message: \n");
	init(s);
	printf("Show ran over :\n");
	Show(s);
	printf("SortShow ran over :\n");
	SortShow(s);
	return 0;
}

A lot better.

The final assessment was successful.

Guess you like

Origin blog.csdn.net/yooppa/article/details/112406957