// CSE143 Sp01 Homework 2 Sample Solution // location.cpp - implementation of class Location // HP 4/01 #include #include using namespace std; #include "location.h" const double PI = 3.1415926535; // Construct a Location with coordinates Location::Location(double xloc, double yloc) { x = xloc; y = yloc; } // Default constructor - initialize this Location to <0,0> Location::Location() { x = 0.0; y = 0.0; } // = Distance from this Location to Location other double Location::distanceTo(Location other) { double dx = x - other.x; double dy = y - other.y; return sqrt(dx*dx + dy*dy); } // compass directions const string direction[] = {"north", "northeast", "east", "southeast", "south", "southwest", "west", "northwest"}; // = Direction from this Location to Location other, as a string: // north, northeast, east, southeast, south, southwest, west, northwest string Location::directionTo(Location other) { // strategy: calculate the angle between 0 and 360, increase by 22.5 degrees // modulo 360 and round to the nearest int to get a number between 0 and 45 for // north, 45 to 90 for northeast, etc., then divide by 45 to get the index of // the appropriate word in array directions. double a; // angle from north +-180 double angle; // angle from 0-360 int deg; // adjusted angle a = atan2(other.x - x, other.y - y) * 180 / PI; if (a > 0) { angle = a; } else { angle = 360.0 + a; } deg = ((int) (angle + 22.5 + 0.5)) % 360; return direction[deg/45]; }