21xrx.com
2025-06-25 03:37:05 Wednesday
登录
文章检索 我的文章 写文章
C++程序:求三角形面积
2023-06-27 01:02:54 深夜i     29     0
C++ 三角形 面积 计算 公式

三角形是几何图形中最为基本和重要的图形之一,计算三角形的面积也是学习 C++ 编程必要的知识点。本文将介绍如何使用 C++ 编程语言编写计算三角形面积的程序。

计算三角形面积的公式为 S = 1/2 * b * h,其中 b 表示三角形底边的长度,h 表示三角形高的长度。因此,我们的第一步是输入三角形的底边和高。

#include <iostream>
using namespace std;
int main()
  float base

接下来,我们需要按照公式计算三角形的面积,并将计算结果输出。在 C++ 中,我们可以使用 cout 语句输出结果。

#include <iostream>
using namespace std;
int main()
{
  float base, height, area;
  cout << "Please enter the base and height of the triangle: ";
  cin >> base >> height;
  area = 0.5 * base * height;
  cout << "The area of the triangle is: " << area << endl;
  return 0;
}

最后,我们需要进行一些简单的格式化操作,使输出更加美观。例如,我们可以添加输出的单位,如下所示:

#include <iostream>
using namespace std;
int main()
{
  float base, height, area;
  cout << "Please enter the base and height of the triangle (in cm): ";
  cin >> base >> height;
  area = 0.5 * base * height;
  cout << "The area of the triangle is: " << area << " sq.cm" << endl;
  return 0;
}

以上代码就是 C++ 程序计算三角形面积的完整代码。通过这篇文章的学习,我们了解了 C++ 编程语言的基本语法和操作方法,也掌握了计算三角形面积的方法。希望这篇文章对初学者有所帮助。

  
  

评论区