显示数组中的学生 ID 和最高分

Display Student ID and highest score from an array

本文关键字:ID 最高分 数组 显示      更新时间:2023-10-16

我在弄清楚如何正确显示学生的 ID 以及 10 名学生中的最高分时遇到了问题。对于考试,如果学生 4 的分数最高,则会显示该学生的 ID 和他们的分数。如果可能的话,我还想添加学生的名字和姓氏。我的代码如下:

// HW2.cpp : This file contains the 'main' function. Program execution begins and ends there.
#include <iostream>
using namespace std;
double TestScore(double score);
struct studentType {
string studentFName;
string studentLName;
double testScore;
int studentID;
double highScore;
};
int main()
{
// # of students
studentType student[10];
// For loop to get user input for the 10 students
for (int i = 0; i < 10; i++) {
cout << "Student ID: ";
cin >> student[i].studentID;
cout << "Student First Name: ";
cin >> student[i].studentFName;
cout << "Student Last Name: ";
cin >> student[i].studentLName;
cout << "Student's Test Score: ";
cin >> student[i].testScore;
cout << endl;
//Calls TestScore function
student[i].testScore = TestScore(student[i].testScore);
}
//Displays student ID and score v code that I need help on
//cout <<student[i].studentID << " has the highest score, which is "<< TestScore;
}
double TestScore(double score)
{
double newScore = 0;
//Determines student with highest score
for (int n = 0; n < 10; n++) {
if (score > newScore)
{
newScore = score;
}
}
return newScore;
}

它需要: 1(将学生的数据读入数组。 2(找到最高的考试分数。 3(打印考试成绩最高的学生姓名。

你的TestScore函数实际上什么都不做。我已经修改了您的代码,使其具有一个函数,该函数返回得分最高的学生的索引。然后,使用此索引可以访问数组的该元素,并打印出其详细信息。

#include <iostream>
using namespace std;
struct studentType {
string studentFName;
string studentLName;
double testScore;
int studentID;
double highScore;
};
int getBestStudent( studentType student[10] );
int main() {
// # of students
studentType student[10];
// For loop to get user input for the 10 students
for ( int i = 0; i < 10; i++ ) {
cout << "Student ID: ";
cin >> student[i].studentID;
cout << "Student First Name: ";
cin >> student[i].studentFName;
cout << "Student Last Name: ";
cin >> student[i].studentLName;
cout << "Student's Test Score: ";
cin >> student[i].testScore;
cout << endl;
}
// Displays student ID and score v code that I need help on
int best = getBestStudent( student );
cout <<student[best].studentFName << " " << student[best].studentLName << " has the highest score, which is "<< student[best].testScore;
}
int getBestStudent( studentType student[10] ) {
int best = 0;
//Determines student with highest score
for ( int n = 1; n < 10; n++ ) {
if ( student[n].testScore > student[best].testScore ) {
best = n;
}
}
return best;
}```