struct stu{ char *name; //姓名 int num; //學號 int age; //年齡 char group; //所在小組 float score; //成績 }class[5];表示一個班級有5個學生。
struct stu{ char *name; //姓名 int num; //學號 int age; //年齡 char group; //所在小組 float score; //成績 }class[5] = { {"Li ping", 5, 18, 'C', 145.0}, {"Zhang ping", 4, 19, 'A', 130.5}, {"He fang", 1, 18, 'A', 148.5}, {"Cheng ling", 2, 17, 'F', 139.0}, {"Wang ming", 3, 17, 'B', 144.5} };當對數組中全部元素賦值時,也可不給出數組長度,例如:
struct stu{ char *name; //姓名 int num; //學號 int age; //年齡 char group; //所在小組 float score; //成績 }class[] = { {"Li ping", 5, 18, 'C', 145.0}, {"Zhang ping", 4, 19, 'A', 130.5}, {"He fang", 1, 18, 'A', 148.5}, {"Cheng ling", 2, 17, 'F', 139.0}, {"Wang ming", 3, 17, 'B', 144.5} };
class[4].score;
修改 Li ping 的學習小組:class[0].group = 'B';
#include <stdio.h> struct{ char *name; //姓名 int num; //學號 int age; //年齡 char group; //所在小組 float score; //成績 }class[] = { {"Li ping", 5, 18, 'C', 145.0}, {"Zhang ping", 4, 19, 'A', 130.5}, {"He fang", 1, 18, 'A', 148.5}, {"Cheng ling", 2, 17, 'F', 139.0}, {"Wang ming", 3, 17, 'B', 144.5} }; int main(){ int i, num_140 = 0; float average, sum = 0; for(i=0; i<5; i++){ sum += class[i].score; if(class[i].score < 140) num_140++; } printf("sum=%.2f\naverage=%.2f\nnum_140=%d\n", sum, sum/5, num_140); return 0; }運行結果: