C7-結構體

一、結構體聲明
二、結構體定義
三、結構體應用
四、結構體與數組

代碼:

// struct 結構體名
// {
//   類型說明符 成員名;
//   ... ...
//   類型說明符 成員名;
// };

//typedef struct student
//{
// short num;
// char name[20];
// char sex;
// float score;
//} a;

//typedef struct rectangle
//{
// int len;
// int wid;
//} a;

typedef struct student
{
short age;
char name[20];
float score;
} stu;

int main(int argc, const char * argv[]) {

// 重定義名字
// 關鍵字 已存在名 新名字

// typedef int apple;

// typedef struct rectangle a;

// //數據類型:struct student
// //變量名:stu
// //初值:{1, “little apple”, ‘m’, 99.8}–>按聲明順序, –>對應聲明中的類型
// a stu = {1, “little apple”, ‘m’, 99.8};
//
// //使用結構體變量
// //變量名.成員
// stu.num = 59;
// strcpy(stu.name, “abc”);
// printf(“%d\n”, stu.num);
// printf(“%s\n”, stu.name);

// a rec = {3, 4};
// printf(“%d %d “, rec.len, rec.wid);

// apple a = 0;
// int b = 3;
// a = 5;
// printf(“%d %d\n”, a, b);

// stu a = {15, “zhangsan”, 60.00};
// stu b = {16, “lisi”, 70.00};
// stu c = {17, “wangwu”, 80.00};
// //stu temp = {0};
// //temp = a.score > b.score ? a : b;
// //temp = temp.score > c.score ? temp : c;
// //printf(“%d %s %.2f\n”, temp.age, temp.name, temp.score);
// int max = 0;
// float gra = 0;
// max = a.age > b.age ? a.age : b.age;
// max = max > c.age ? max : c.age;
// printf(“最大年齡是:%d\n”, max);
// gra = a.score > b.score ? a.score : b.score;
// gra = gra > c.score ? gra : c.score;
// printf(“最高成績是:%.2f\n”, gra);

// a st = {0};
// long ret = sizeof(st);
// //計算佔內存空間大小
// printf(“%ld\n”, ret);

  // 有5名學生保存在結構體數組中,編程查找成績最高者,輸出該學生全部信息

// stu stu1 = {15, “zhangsan”, 60.00};
// stu stu2 = {16, “lisi”, 70.00};
// stu stu3 = {17, “wangwu”, 80.00};
// stu stu4 = {18, “zhaoliu”, 90.00};
// stu stu5 = {19, “qianqi”, 30.00};
// stu temp = {0};
// temp = stu1.score > stu2.score ? stu1 : stu2;
// temp = temp.score > stu3.score ? temp : stu3;
// temp = temp.score > stu4.score ? temp : stu4;
// temp = temp.score > stu5.score ? temp : stu5;
// printf(“%d %s %.2f\n”, temp.age, temp.name, temp.score);
// stu gra[5] = {stu1, stu2, stu3, stu4, stu5};
// stu stutemp = {0};
// for (int i = 0; i < 4; i++) {
// for (int j = 0; j < 4 - i; j++) {
// if (gra[j].score < gra[j + 1].score) {
// stutemp = gra[j];
// gra[j] = gra[j + 1];
// gra[j + 1] = stutemp;
// }
// }
// }
// for (int i = 0; i < 5; i++) {
// printf(“%d %s %.2f\n”, gra[i].age, gra[i].name, gra[i].score);
// }

//結構體數組定義並初始化

// Student stu[3] = {
// {15, “zhangsan1”, 61.00};
// {16, “zhangsan2”, 62.00};
// {17, “zhangsan3”, 63.00};
// };
// //訪問結構體數組中的元素/成員
// stu[1].score = 99.9;

return 0;

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章