I am a brand-new student of C++ and working through some of the practice exercises in a book called Engineering Problem Solving with C++ by Dolores Etter.
I'm currently stuck on an exercise where I have to write a program that determines if a given point lies inside or outside of a defined triangle.
In my approach, I used Heron's formula for the area of a triangle based on the lengths of its sides. In my program the sides (and subsequently, the area) of the triangle in questions are constructed via 3 defined points A, B, and C, and then a given point 'P' (called "input") is used to construct triangles PAB PAC and PBC.
The idea is that if the area of PAB + PAC + PBC = Area of ABC, then the point must be inside the triangle.
I went pretty carefully through the equations that I used, calculating it all out by hand, and I cannot see why the program keeps returning the wrong answer.
For instance, it tells me that for A (0,0), B (0,3), and C (3,0), that input (1,1) is outside the triangle. Which is not true.
I am totally new to this and have no idea what is wrong. Can you take a look at the code and tell me what my error might be?
#include <iostream>
#include <cmath>
using namespace std;
struct Point {
double x, y;
auto operator - (Point const &that) const -> double {
double yy = y - that.y;
double xx = x - that.x;
return sqrt(xx * xx + yy * yy);
}
};
int main() {
Point A{0,0}, B{0,3}, C{3,0}, input{1,1.25};
double AreaMain, AreaPAB, AreaPBC, AreaPAC;
double lengthAB = (A - B);
double lengthAC = (A - C);
double lengthBC = (B - C);
double lengthPA = (input - A);
double lengthPB = (input - B);
double lengthPC = (input - C);
double semipMain = (lengthAB + lengthAC + lengthBC)/2.0;
double semipPAB = (lengthPA + lengthPB + lengthAB)/2.0;
double semipPBC = (lengthPB + lengthPC + lengthBC)/2.0;
double semipPAC = (lengthPA + lengthPC + lengthAC)/2.0;
AreaMain = sqrt(semipMain*(semipMain - lengthAB)*(semipMain - lengthAC)*(semipMain - lengthBC));
AreaPAB = sqrt(semipPAB*(semipPAB - lengthPA)*(semipPAB - lengthPB)*(semipPAB - lengthAB));
AreaPBC = sqrt(semipPBC*(semipPBC - lengthPB)*(semipPBC - lengthPC)*(semipPBC - lengthBC));
AreaPAC = sqrt(semipPAC*(semipPAC - lengthPA)*(semipPAC - lengthPC)*(semipPAC - lengthAC));
if ((AreaPAB + AreaPBC + AreaPAC) == AreaMain)
cout << "The given point is inside the triangle" << endl;
else
cout << "The given point is outside the triangle" << endl;
return 0;
}
I think it must be something I don't know about the way C++ works, because the math has been verified! Is it something to do with the formula I am using for the semiperimeter of each triangle? An error implementing Heron's formula?