If I see it correctly, the formula
angle = atan2(x, -y) * 180.0/M_PI;
should work in all quadrants, making all the if
statements unnecessary.
atan2(y, x)
returns the angle between the vector (x, y)
and the positive x-axis, the return value is always between -pi
and pi
.
Replacing (y, x)
by (x, -y)
in the arguments
means that the vector is rotated by 90 degrees, therefore the result of the above formula
is the angle measured to the negative y-axis, which is what you wanted.
Update (according to "edit2" in the question): If the requirement is "south = 0 deg", "east = -90 deg", "west = +90 deg" then the formula would be
angle = atan2(-x, -y) * 180.0/M_PI;