patterncMinor
Calculates best angle on path and approximates cardinal direction
Viewed 0 times
cardinalpathdirectionandangleapproximatescalculatesbest
Problem
This program uses the C language. What's used are two points, and the usage of the inverse tan function finds the angle of the line between the two points. Afterward, it finds the cardinal direction on the plane. -y is south, +y is north. It seems to work quite well. However, I want to find what is unconventional of my program. I want to learn to write good code and this is a good step towards it.
#include
#include
#include
#include
#define PI 3.14159265
int cardinal(double degrees)
{
// 0 is North
// 1 is North-east
// 2 is East
// 3 is South-east
// 4 is South
// 5 is South-west
// 6 is West
// 7 is North-west
int cardinal;
if (degrees >= -22.5 && degrees 22.5 && degrees = 67.5 && degrees 112.5 && degrees = -157.5 && degrees -157.5 && degrees = -112.5 && degrees -67.5 && degrees < -22.5)
cardinal = 7;
return cardinal;
}
char* direction(int cardinal)
{
if (cardinal == 0)
return "north";
if (cardinal == 1)
return "northeast";
if (cardinal == 2)
return "east";
if (cardinal == 3)
return "southeast";
if (cardinal == 4)
return "south";
if (cardinal == 5)
return "southwest";
if (cardinal == 6)
return "west";
if (cardinal == 7)
return "northwest";
}
int main()
{
int xpl = 494, ypl = 105;
int xcom = 152, ycom = -168;
double degrees;
double radians;
int num;
double CONS = 180.0 / PI;
int xo = xcom - xpl;
int yo = ycom - ypl;
radians = atan2(yo, xo);
degrees = radians * CONS;
num = cardinal(degrees);
printf("The angle to travel in is %f (degrees) %f (radians)\n", degrees, radians);
printf("Numerical direction: %d", num);
printf("\nDirection: %s", direction(num));
return 0;
}Solution
Two suggestions:
- in the
cardinalfunction, return the number rather than setting a variable, so you shortcut all the otherifstatements. You could further optimize that by doing a binary rather than a linear search.
- your
directionfunction could be replaced by an array:int directions[8] = {"north", "northeast", ... };. Then the lookup is simplydirections[cardinal]
Context
StackExchange Code Review Q#160497, answer score: 3
Revisions (0)
No revisions yet.