Points of Reference

 

Modules - Structured Programming 2

 

Teacher’s Notes:

========================================================================

This exercise gets students using the math library while also using IF statements.  It is a fairly easy assignment that I use to introduce students to using built in math statements.  In the solution, I use x * x instead of x² but you can easily use whatever power function your programming language allows.

 

Assignment:

========================================================================

 

In geometry, a triangle can be described by using 3 coordinate pairs to show the position for each of its vertices.  For example, a triangle could be drawn with vertices A(1,1), B(3,4) and C(8,-2).  

To find the distance between two points (A and B), we use the equation: 


distance = square root of ( (Bx - Ax)² + (By - Ay)² )


In C++ the square root of a number can be found by (a) importing that math library <math.h> and then (b) using the command sqrt(x), where x is the number we want to find the square root of.


Write a program that will read in the coordinates of three points of a triangle in the order:

Ax, Ay, Bx, By, Cx and Cy.  

The program will then output the side of the triangle that is the longest.  The output will be either "AB", "AC", "BC", or "There is no longest line.".

 

 

Solution (C++):

========================================================================

 
#include <iostream>
#include <math.h>
 
using namespace std;

int main() {

  int Ax, Ay, Bx, By, Cx, Cy;
  cin >> Ax;
  cin >> Ay;
  cin >> Bx;
  cin >> By;
  cin >> Cx;
  cin >> Cy;
 
  double distanceAB = sqrt( (Bx-Ax)*(Bx-Ax)+(By-Ay)*(By-Ay) );
  double distanceAC = sqrt( (Cx-Ax)*(Cx-Ax)+(Cy-Ay)*(Cy-Ay));
  double distanceBC = sqrt( (Bx-Cx)*(Bx-Cx)+(By-Cy)*(By-Cy) );
  
  if(distanceAB > distanceBC && distanceAB > distanceAC)
    cout << "AB" << endl;
  else if (distanceAC > distanceAB && distanceAC > distanceBC)
    cout << "AC" << endl;
  else if (distanceBC > distanceAC && distanceBC > distanceAB)
    cout << "BC" << endl;
  else
    cout << "There is no longest line." << endl;
 
  
}