通过键盘输入一个整数n,代表有n 个学生,接下来输入每一个学生的名字以及他的总成绩,然后输出其中总成绩最低的学生的名字和他的成绩
#include <iostream>
#include <string>
using namespace std;
int main()
{
int n;
cout << "请输入学生人数:";
cin >> n;
string minName;
int minScore = INT_MAX;
for (int i = 0; i < n; i++) {
string name;
int score;
cout << "请输入学生姓名:";
cin >> name;
cout << "请输入学生成绩:";
cin >> score;
if (score < minScore) {
minScore = score;
minName = name;
}
}
cout << "总成绩最低的学生是:" << minName << endl;
cout << "他的成绩是:" << minScore << endl;
return 0;
}
【以下回答由 GPT 生成】
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct Student {
string name;
int score;
};
int main() {
int n;
cout << "请输入学生人数: ";
cin >> n;
vector<Student> students(n);
for (int i = 0; i < n; i++) {
cout << "请输入学生" << i + 1 << "的姓名: ";
cin >> students[i].name;
cout << "请输入学生" << i + 1 << "的总成绩: ";
cin >> students[i].score;
}
int minScoreIndex = 0;
int minScore = students[0].score;
for (int i = 1; i < n; i++) {
if (students[i].score < minScore) {
minScore = students[i].score;
minScoreIndex = i;
}
}
cout << "总成绩最低的学生是:" << students[minScoreIndex].name << ",成绩是:" << students[minScoreIndex].score << endl;
return 0;
}
解决思路: 1. 首先输入学生人数n。 2. 创建一个大小为n的vector,用来存储学生信息(姓名和总成绩)。 3. 使用循环依次输入每个学生的姓名和总成绩。 4. 初始化最低成绩的下标为0,并将第一个学生的总成绩设为最低成绩。 5. 遍历所有学生,如果发现某个学生的总成绩比当前最低成绩还低,则更新最低成绩和对应的下标。 6. 输出总成绩最低的学生的姓名和成绩。
【相关推荐】