结构体是复杂数据结构的基础
定义学生信息如下:
struct stu
{
int stuId;
char name[5];
int score;
};
#include <stdio.h>
#include <string.h>
#define LENGTH 20
void main()
{
struct stu //定义一个结构体
{
int stuid; //包含一个ID属性
char name[LENGTH]; //包含一个名字属性
int score; //包含一个分数属性
}s[5]={ {11,"xiaoming",78},
{13,"jingjing",88},
{16,"vivian",98},
{19,"tony",60},
{90,"duno",59} }; //创建一个学生结构体数组,并且为这五个学生赋初值
int i,j,tmpid,tmpscore; //定义几个整型变量,i,j用来进行循环控制,tmpid和tmpscore进行临时值存放
char tmps[LENGTH]; //进行字符串的临时存放
/* printf("please input totle 5 students info:\n\n"); //从终端循环读入五个学生的信息,并且保存到前面定义的结构体数组中
for (i=0;i<5;i++)
{
printf("please input the %d student id:\n",i+1);
scanf("%d",&s[i].stuid); //结构体中属性的正确引用方法,通过.来引用
printf("please input the %d student name:(less then %d length)\n",i+1,LENGTH);
scanf("%s",&s[i].name);
printf("please input the %d student score:(int type)\n",i+1);
scanf("%d",&s[i].score);
}
*/
printf("\nThe totle 5 students info are:\n%10s%20s%10s\n","stuid","name","score"); //使用格式化输出可以让信息以更友好的方式展示
for (i=0;i<5;i++) printf("%10d%20s%10d\n",s[i].stuid,s[i].name,s[i].score); //使用格式化输出可以让信息以更友好的方式展示
printf("\nAll student info whos score above 80 are:\n%10s%20s%10s\n","stuid","name","score");
for (i=0;i<5;i++) if (s[i].score > 80) printf("%10d%20s%10d\n",s[i].stuid,s[i].name,s[i].score); //判断,分数大于80,进行打印
for (i=0;i<4;i++) //使用冒泡排序的思想基于分数进行排序
{
for(j=i+1;j<5;j++)
{
if(s[i].score < s[j].score)
{
tmpid=s[i].stuid;
s[i].stuid=s[j].stuid;
s[j].stuid=tmpid;
strcpy(tmps,s[i].name);
strcpy(s[i].name,s[j].name);
strcpy(s[j].name,tmps);
tmpscore=s[i].score;
s[i].score=s[j].score;
s[j].score=tmpscore;
}
}
}
printf("\nAll student sort resault base on score are:\n%10s%20s%10s\n","stuid","name","score");
for (i=0;i<5;i++) printf("%10d%20s%10d\n",s[i].stuid,s[i].name,s[i].score);
}
思路比较简单和直接,主要是在巩固结构体的定义,属性的调用,基于其中部分属性值的过滤,与排序
原文地址http://soft.dog/2016/11/24/c-basic-16/
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。