21xrx.com
2024-09-20 00:54:43 Friday
登录
文章检索 我的文章 写文章
C++计算三个学生的平均成绩
2023-07-05 19:35:37 深夜i     --     --
C++ 计算 学生 平均成绩

C++是一种广泛使用的编程语言,它可以用于各种计算和编程任务。在本文中,我们将使用C++编写一个程序,计算三个学生的平均成绩。

首先,我们需要定义三个变量,分别代表三个学生的成绩。这些变量可以是整数或浮点数类型,根据你的需要选择最合适的类型。在这个例子中,我们将使用浮点数类型表示分数。

接下来,我们需要为每个变量赋值,表示每个学生的成绩。这可以通过从控制台输入数字完成。使用C++的标准输入流(cin)来获取用户输入的值,如下所示:


float score1, score2, score3;

cout << "Enter the first student's score: ";

cin >> score1;

cout << "Enter the second student's score: ";

cin >> score2;

cout << "Enter the third student's score: ";

cin >> score3;

在这段代码中,我们首先定义了三个浮点数类型的变量score1、score2和score3。然后使用cout将消息输出到控制台,提示用户输入每个学生的成绩。使用cin获取输入值,赋值给对应的变量。

现在,我们有了三个学生的成绩,接下来我们需要计算它们的平均值。这可以通过将三个成绩相加,然后将结果除以3来完成,如下所示:


float average = (score1 + score2 + score3) / 3;

cout << "The average score is: " << average << endl;

在这段代码中,我们首先定义了一个名为average的浮点数类型的变量。我们将三个学生的成绩相加,然后将结果除以3,得到平均值。最后,我们使用cout将平均值输出到控制台。

现在,我们已经完成了计算三个学生的平均成绩的整个过程。下面是完整的C++代码:


#include<iostream>

using namespace std;

int main()

{

  float score1, score2, score3;

  cout << "Enter the first student's score: ";

  cin >> score1;

  cout << "Enter the second student's score: ";

  cin >> score2;

  cout << "Enter the third student's score: ";

  cin >> score3;

  float average = (score1 + score2 + score3) / 3;

  cout << "The average score is: " << average << endl;

  return 0;

}

让我们来运行这个程序,看看它的输出结果:


Enter the first student's score: 85

Enter the second student's score: 78

Enter the third student's score: 92

The average score is: 85

根据这三个学生的成绩,我们可以计算出他们的平均成绩为85。这个例子仅仅展示了C++的基本语法和一些流程控制语句,但它们是最基本且至关重要的部分,值得学习和掌握。

  
  

评论区

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