holyya.com
2025-09-04 13:51:41 Thursday
登录
文章检索 我的文章 写文章
C++编程:使用友元函数输入学生成绩,求总分和平均分
2023-07-09 00:27:17 深夜i     --     --
C++ 编程 友元函数 学生成绩 总分 平均分

C++是一种强大的编程语言,它可以广泛应用于多个领域,其中包括学生管理。在许多学生管理系统中,需要输入学生的成绩,并计算总分和平均分。在这种情况下,使用C++编程可以非常方便地完成这项工作。

友元函数是一种C++编程中非常有用的概念,允许一个非成员函数访问一个类的私有成员。在学生成绩输入和计算总分和平均分的过程中,我们可以使用友元函数来完成这项任务。

下面展示了如何使用友元函数输入学生成绩并计算总分和平均分:


#include <iostream>

#include <string>

using namespace std;

class Student {

private:

  string name; // 学生姓名

  int chinese; // 语文成绩

  int math;  // 数学成绩

  int english; // 英语成绩

  friend int sum(Student stu); // 友元函数,计算总分

  friend float average(Student stu); // 友元函数,计算平均分

public:

  void setScore(string n, int c, int m, int e)

    name = n;

    chinese = c;

    math = m;

    english = e;

  

};

int sum(Student stu) {

  return stu.chinese + stu.math + stu.english;

}

float average(Student stu) {

  return sum(stu) / 3.0; // 平均分 = 总分 / 3

}

int main() {

  Student stu;

  cout << "请输入学生姓名、语文成绩、数学成绩、英语成绩:" << endl;

  string name;

  int chinese, math, english;

  cin >> name >> chinese >> math >> english;

  stu.setScore(name, chinese, math, english);

  cout << "总分:" << sum(stu) << endl;

  cout << "平均分:" << average(stu) << endl;

  return 0;

}

在上面的代码中,我们定义了一个Student类表示每个学生的信息。该类包含私有成员name、chinese、math、english分别对应学生的姓名、语文、数学、英语成绩。在类的定义中,我们使用friend关键字声明了两个友元函数sum和average,允许它们访问Student类的私有成员。

在主函数中,我们通过从标准输入流中读取学生姓名、语文、数学、英语成绩,创建一个Student对象,然后调用setScore方法设置学生成绩。接着,我们调用sum和average函数分别计算学生的总分和平均分,并输出结果。

使用友元函数能够有效地简化代码,提高程序的清晰程度和执行效率。在学生管理系统中,使用友元函数来输入学生成绩并计算总分和平均分,能够更好地管理和跟踪学生成绩,从而帮助提高学生的学习成绩。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复