Structure practice (2) structure array

After learning the concept of the structure array last time, we can perform the code actual operation on the structure array. You can feel that the combination of the array and the structure will make the code more functional and streamlined.
This sharing is for code display and code analysis.
Code display:
Example:

#include<stdio.h>
struct stu
{
    
    
	int number;
	char name[20];
	int score[5];
}st[10]={
    
    
	{
    
    1001,"zhao",85,64,82,63},
	{
    
    1002,"Qian",92,60,96,67},
	{
    
    1003,"you",99,90,87,90},
	{
    
    1004,"ruan",90,98,87,86},
	{
    
    1005,"zhang",90,87,77,88}
},temp;
int main()
{
    
    
	int i,j;
	int num;
    num=5;

	for(i=0;i<num;i++)
	{
    
    
		st[i].score[4]=0;
		for(j=0;j<4;j++)
		{
    
    
			st[i].score[4]+=st[i].score[j];
		}
	}

	for(i=0;i<num;i++)
	{
    
    
		for(j=0;j<num-i;j++)
		{
    
    
			if(st[j].score[4]<st[j+1].score[4])
			{
    
    
			temp=st[j];
			st[j]=st[j+1];
			st[j+1]=temp;
			}
		}
	}

   printf("学号\t姓名\t成绩1\t成绩2\t成绩3\t成绩4\t总成绩\n");
   for(i=0;i<num;i++)
	  {
    
    
	   printf("%d\t%s\t%d\t%d\t%d\t%d\t%d\n",st[i].number,st[i].name,st[i].score[0],
		   st[i].score[1],st[i].score[2],st[i].score[3],st[i].score[4]);
   }
}

The example is looking at the code modified in the textbook.

Code analysis:

st[10]={ {1001,"zhao",85,64,82,63}, {1002,"Qian",92,60,96,67}, {1003,"you",99,90,87 ,90}, {1004,"ruan",90,98,87,86}, {1005,"zhang",90,87,77,88} },temp; This part is the variable defined by the structure stu, textbook In fact, the main function is defined again, but I like to define it all at once. temp is a temporary variable for exchange. Related to the subsequent bubble sorting of the total score. This part is the total score of four subjects: for(i=0;i<num;i++) { st[i].score[4]=0; for(j=0;j<4;j++) { st[i ].score[4]+=st[i].score[j]; } } score[4] in the loop body is a part of the memory reserved for the total score when the score[5] is defined (the footer is from the four scores The order is 0, 1, 2, 3). From here, you can experience the simplified code effect of using structure arrays, and you don't need to define an array to store this part. The following is the bubble sort: for(i=0;i<num;i++) { for(j=0;j<num-i;j++) { if(st[j].score[4]<st[j+ 1].score[4])
























{ temp=st[j]; st[j]=st[j+1]; st[j+1]=temp; } } } This is more difficult to understand than the previous bubble sorting of one-dimensional arrays. You can still understand it if you read it carefully. The whole code is relatively easy.







Guess you like

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