1、 创建一个对象数组,数组的元素是学生对象,学生的信息包括学号、姓名和成绩(一门课成绩),求其总人数和平均分。(学生对象不得少于5个) 要求学生信息由键盘输入!
#include <iostream>
#include <string>
using namespace std;
class Student {
public:
string id; // 学号
string name; // 姓名
float score; // 成绩
};
int main() {
const int num_students = 5;
Student students[num_students];
// 从键盘输入学生信息
for (int i = 0; i < num_students; i++) {
cout << "请输入第 " << i+1 << " 个学生的信息:" << endl;
cout << "学号:";
cin >> students[i].id;
cout << "姓名:";
cin >> students[i].name;
cout << "成绩:";
cin >> students[i].score;
}
// 计算总人数和平均分
float total_score = 0;
for (int i = 0; i < num_students; i++) {
total_score += students[i].score;
}
float avg_score = total_score / num_students;
// 输出结果
cout << "总人数:" << num_students << endl;
cout << "平均分:" << avg_score << endl;
return 0;
}
int CountNodes(LBTree* lbt)
{
int n = 0;
if (lbt != NULL)
{
++n;
n += CountNodes(lbt->lchild);
n += CountNodes(lbt->rchild);
}
return n;
}
int CountLeaves(LBTree* lbt)
{
int n = 0;
if (lbt != NULL)
{
if (lbt->lchild == NULL && lbt->rchild == NULL)
++n;
n += CountLeaves(lbt->lchild);
n += CountLeaves(lbt->rchild);
}
return n;
}
int CountSingleNode(LBTree* lbt)
{
int n = 0;
if (lbt != NULL)
{
if ((lbt->lchild == NULL && lbt->rchild != NULL) || (lbt->rchild == NULL && lbt->lchild != NULL))
++n;
n += CountSingleNode(lbt->lchild);
n += CountSingleNode(lbt->rchild);
}
return n;
}
int CountDoubleNode(LBTree* lbt)
{
int n = 0;
if (lbt != NULL)
{
if (lbt->lchild != NULL && lbt->rchild != NULL)
++n;
n += CountDoubleNode(lbt->lchild);
n += CountDoubleNode(lbt->rchild);
}
return n;
}
可以使用以下代码创建一个包含多个学生对象的数组:
using namespace std;
class Student { private: int id; string name; double score; public: // 构造函数 Student(int i, string n, double s) { id = i; name = n; score = s; } // getter和setter int getId() { return id; } void setId(int i) { id = i; } string getName() { return name; } void setName(string n) { name = n; } double getScore() { return score; } void setScore(double s) { score = s; } };
int main() { const int NUM_OF_STUDENTS = 5; Student students[NUM_OF_STUDENTS];
// 通过键盘输入学生信息,并存入数组中
for (int i = 0; i < NUM_OF_STUDENTS; i++) {
// 输入学生信息
cout << "请输入第" << i+1 << "个学生的学号、姓名和成绩:" << endl;
int id;
string name;
double score;
cin >> id >> name >> score;
// 将学生信息存入数组
Student student(id, name, score);
students[i] = student;
}
// 计算学生总人数和平均成绩
int numOfStudents = NUM_OF_STUDENTS;
double sumScore = 0;
for (int i = 0; i < NUM_OF_STUDENTS; i++) {
sumScore += students[i].getScore();
}
double avgScore = sumScore / numOfStudents;
// 输出结果
cout << "学生总人数为:" << numOfStudents << endl;
cout << "平均成绩为:" << avgScore << endl;
return 0;
}
这里定义了一个Student类,包含学号、姓名和成绩,然后创建一个包含5个Student对象的数组。通过循环,读入每个学生的信息,并存入数组中。最后,计算学生总人数和平均成绩,并输出结果。