Examples C++

Area of a Triangle Given by Three Points

In this C++ example, we demonstrate how to write a function to calculate the area of a triangle given by three points in the plane. The area function calculates the positive area from the signed area formula. In our main function, we call the Area() function twice and output the results.

Code:

#include <iostream>

double Area(double dX0, double dY0, double dX1, double dY1, double dX2, double dY2)
{
    double dArea = ((dX1 - dX0)*(dY2 - dY0) - (dX2 - dX0)*(dY1 - dY0))/2.0;
    return (dArea > 0.0) ? dArea : -dArea;
}

int main()
{
    using namespace std;

    // Calculate the area for two triangles
    cout << "Area = " << Area(0.0, 0.0, 0.0, 1.0, 1.0, 1.0) << endl;
    cout << "Area = " << Area(1.0, 2.0, 3.0, 1.0, 4.0, 3.0) << endl;

    return 0;
}

Output:

Output
 

© 2007–2024 XoaX.net LLC. All rights reserved.