-
>
>
>
>
Programming Assignments >
Assignment 1 - Distance Calculator
Objectives
- to write a simple C++ program
- to compile C++ programs using the Unix command line
- to use C++ strings
- to use C++ I/O streams
- to use standard C libraries within C++
Introduction
Geographic coordinates are given using longitude, which is a measure of how far
east or west from a fixed line of longitude a place is, and latitude,
which measures how far north or south of the equator a place is. Longitude
and latitude are often expressed in degrees. Given such a representation
one can compute the distance between two points ($lat1$, $lon1$)
($lat2$, $lon2$) by
- first computing the colatitudes $a$ and $b$
of each point; the colatitude is the angle between the
point and the North Pole with the center of the Earth as the vertex
and can be computed as $90 - lat$,
- computing the difference in longitude $C$ between the two points,
- computing the size $c$ of the angle between the two points with
the center of the Earth as the vertex
$$ c = cos^{-1}(cos(a)cos(b) + sin(a)sin(b)cos(C))$$
(where the relevant C functions expect the angles to be expressed in radians)
- and finally converting that angle to a distance by multiplying by
the radius of the Earth, which is 3959 miles.
(Note that we are making the simplifying assumption that the Earth is a
sphere.)
Assignment
Write a C++ program that reads from standard input the coordinates
of two points on Earth and outputs the distance between them in miles.
The input will be given on four lines:
the latitude and longitude of one point on separate lines and in that
order, then the latitude and longitude of a second point. Each line
will be either decimal degrees, integer degrees and decimal minutes,
or integer degrees and minutes and decimal seconds. You may assume
that the values given are within the range +/- 90 degrees for latitude
and +/- 180 degrees for longitude and the minus sign, when present,
is on the degrees component. For example,
the following would be legal input:
51.4826
0
41 18.5
-72 55 40.44
(note that when the degrees are negative the negative distributes through the
minutes and seconds, so the decimal equivalent of -72 55 40.44
is -72.9279). If the input is not in this format or violates
any permitted assumptions then your program must
behave gracefully – it must not crash or go into an infinite loop.
The output should be in the default format for a double
.
Your submission must include a makefile that produces an executable file
named Distance
when make
is run with no arguments.
Example
If the input file lon_nhv.txt
contains
51.4826
0
41 18.5
-72 55 40.44
Then the execution of the program would be as follows.
$ ./Distance < lon_nhv.txt
3397.54