一、知识点整理
1. 结构体数组 + 成员数组的下标分工
| 写法 | 用途 |
| st[i].score[0] | 固定科下标,变化学生下标 → 求某一科的全班总分 |
| st[i].score[j] | 两层都变化 → 逐位学生把三科都走到 |
想清楚'谁在变、谁不变',是写好这类循环的关键。
2. 先用一句算出总分
int total = st[i].score[0] + st[i].score[1] + st[i].score[2]; 把三位学生的三科直接相加得到个人总分,后面判断、比较都用它,代码更清爽。
3. 统计与打擂台的通用套路
统计:满足条件就 count++。找最值:先立擂主,再逐位挑战,同时用两个变量分别记住最高分和它对应的名字。
最高分和名字必须同时更新,否则最后会出现'分数和人对不上'的情况。
4. 整数除法与平均分
总分 275 除以 3 得 91.67,但 total / 3 得到的却是 91——两边都是整数时,结果只保留整数部分。
案例一 求某一科的全班总分
成绩册上排好了三位学生的三科成绩。老师先想看第一科的全班总分是多少。
struct Student{
string name;
int score[3];
};
Student st[3];
st[0].name = "小明"; st[0].score[0]=80; st[0].score[1]=90; st[0].score[2]=85;
st[1].name = "小红"; st[1].score[0]=95; st[1].score[1]=88; st[1].score[2]=92;
st[2].name = "小刚"; st[2].score[0]=70; st[2].score[1]=75; st[2].score[2]=80;
int sum = 0;
for(int i = 0; i < 3; i++){
sum = sum + st[i].score[0];
}
cout << sum << endl;
单选题
判断题
案例二 用总分做条件统计
老师想评出'三科总分不低于 260 分'的优秀学生,看看有几位。
struct Student{
string name;
int score[3];
};
Student st[3];
st[0].name = "小明"; st[0].score[0]=80; st[0].score[1]=90; st[0].score[2]=85;
st[1].name = "小红"; st[1].score[0]=95; st[1].score[1]=88; st[1].score[2]=92;
st[2].name = "小刚"; st[2].score[0]=70; st[2].score[1]=75; st[2].score[2]=80;
int count = 0;
for(int i = 0; i < 3; i++){
int total = st[i].score[0] + st[i].score[1] + st[i].score[2];
if(total >= 260){
count++;
}
}
cout << count << endl;
单选题
判断题
案例三 找出总分最高的学生
老师还想知道谁的总分最高,并且要同时报出他的名字。
struct Student{
string name;
int score[3];
};
Student st[3];
st[0].name = "小明"; st[0].score[0]=80; st[0].score[1]=90; st[0].score[2]=85;
st[1].name = "小红"; st[1].score[0]=95; st[1].score[1]=88; st[1].score[2]=92;
st[2].name = "小刚"; st[2].score[0]=70; st[2].score[1]=75; st[2].score[2]=80;
int best = -1;
string who = "";
for(int i = 0; i < 3; i++){
int total = st[i].score[0] + st[i].score[1] + st[i].score[2];
if(total > best){
best = total;
who = st[i].name;
}
}
cout << who << " 总分 " << best << endl;
单选题
判断题
案例四 逐位学生算平均分
老师最后要给每位学生算一张个人的平均分小条。
struct Student{
string name;
int score[3];
};
Student st[3];
st[0].name = "小明"; st[0].score[0]=80; st[0].score[1]=90; st[0].score[2]=85;
st[1].name = "小红"; st[1].score[0]=95; st[1].score[1]=88; st[1].score[2]=92;
st[2].name = "小刚"; st[2].score[0]=70; st[2].score[1]=75; st[2].score[2]=80;
for(int i = 0; i < 3; i++){
int total = st[i].score[0] + st[i].score[1] + st[i].score[2];
cout << st[i].name << " 平均 " << total / 3 << endl;
}
单选题
判断题