定义一个c++函数,从键盘上输出若干个学生的成绩,统计出平均成绩,并输出低于平均成绩的学生成绩,输入负数结束
时间: 2024-10-10 16:13:05 浏览: 37
在C++中,你可以创建一个函数来满足这个需求。首先,你需要定义一个结构体表示学生,包含姓名和成绩。然后定义一个函数接收用户输入,处理计算平均分以及筛选低分的学生。下面是一个简单的例子:
```cpp
#include <iostream>
#include <vector>
using namespace std;
struct Student {
string name;
int score;
};
double calculateAverage(vector<Student>& students) {
double sum = 0;
for (const auto& student : students) {
sum += student.score;
}
return sum / students.size();
}
void printBelowAverage(const vector<Student>& students, const double average) {
cout << "Students with scores below the average of " << average << ":" << endl;
for (const auto& student : students) {
if (student.score < average) {
cout << "Name: " << student.name << ", Score: " << student.score << endl;
}
}
}
int main() {
vector<Student> studentList;
double currentScore;
while (true) {
cout << "Enter a student's name (or -1 to exit): ";
getline(cin, studentList.back().name);
cout << "Enter their score: ";
cin >> currentScore;
if (currentScore == -1) break; // 输入负数退出循环
studentList.back().score = currentScore;
}
double avg = calculateAverage(studentList);
printBelowAverage(studentList, avg);
return 0;
}
```
在这个程序中,我们首先读取学生名字和分数,直到用户输入-1为止。`calculateAverage`函数会计算所有成绩的总和并除以学生数量得到平均值,而`printBelowAverage`函数则遍历学生列表并打印那些低于平均分的学生。
阅读全文