21xrx.com
2024-09-20 00:59:25 Friday
登录
文章检索 我的文章 写文章
用C++定义学生类并打印数学成绩和排名
2023-07-04 21:16:26 深夜i     --     --
C++ 学生类 数学成绩 排名

C++是一种广泛用于编程的高级语言,它的特点是运行速度较快、语法简洁易懂。在使用C++语言编写程序时,需要定义变量、数组、类等不同的数据类型。在此,我们将使用C++语言定义一个学生类,并打印出学生的数学成绩和排名。

要定义一个学生类,需要考虑学生的属性和行为。学生的属性可以包括姓名、班级、学号、数学成绩等,而学生的行为可以包括打印成绩、计算排名等。

首先,我们定义一个学生类,包含学生的姓名、学号和数学成绩属性:


class Student

public:

  string name;

  int num;

  double math;

;

在定义学生类时,需要使用关键字“class”,并指定公共访问权限,即使用“public:”。

接下来,我们定义一个学生数组,并为每个学生赋值:


int main() {

  Student stu[5];

  stu[0].name = "Tom";

  stu[0].num = 101;

  stu[0].math = 90;

  stu[1].name = "Jack";

  stu[1].num = 102;

  stu[1].math = 85;

  stu[2].name = "Lily";

  stu[2].num = 103;

  stu[2].math = 95;

  stu[3].name = "Lucy";

  stu[3].num = 104;

  stu[3].math = 88;

  stu[4].name = "Bob";

  stu[4].num = 105;

  stu[4].math = 82;

}

上述代码中,我们定义了一个长度为5的学生数组,并分别给每个学生赋值。接下来,我们可以根据数学成绩为学生排名,并打印出学生的数学成绩和排名:


#include <iostream>

#include <algorithm>

using namespace std;

int main() {

  Student stu[5];

  stu[0].name = "Tom";

  stu[0].num = 101;

  stu[0].math = 90;

  stu[1].name = "Jack";

  stu[1].num = 102;

  stu[1].math = 85;

  stu[2].name = "Lily";

  stu[2].num = 103;

  stu[2].math = 95;

  stu[3].name = "Lucy";

  stu[3].num = 104;

  stu[3].math = 88;

  stu[4].name = "Bob";

  stu[4].num = 105;

  stu[4].math = 82;

  sort(stu, stu + 5, [](const Student &a, const Student &b)

    return a.math > b.math;

  );

  for (int i = 0; i < 5; i++) {

    cout << "Name: " << stu[i].name << " Math: " << stu[i].math << " Rank: " << i + 1 << endl;

  }

  return 0;

}

如上述代码所示,我们定义了一个排序函数,并将该函数作为参数传递给了sort()函数,这样就根据数学成绩为学生排名了。最后,我们使用for循环遍历学生数组,并输出每个学生的姓名、数学成绩和排名。

在使用C++定义学生类时,需要考虑到学生的属性和行为,并根据这些属性和行为定义对应的数据类型和函数。通过打印出学生的数学成绩和排名,可以更好地了解每个学生在班级中的学习成绩和水平。

  
  

评论区

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