Thursday, December 16, 2010

How to find angle between hour and minute hands in an analog clock?

Given a simple clock, we have to find the angle between the hour and minute hands. Since this is a deliberate question, we should obviously be ignoring the thickness of the hands in the clock.

We need to understand the following things before we arrive at our solution.
  • The hour hand moves at the rate of 0.5 degrees per minute.
  • The minute hand moves at the rate of 6 degrees per minute.
The reason for the above statements are obvious if you think a layer deep. Now, for the code (works both for C++ and Java)

double angle(int h, int m)
     double hangle = 0.5D * (h*60 + m);
     double mangle = 6*m;
     angle = abs(hangle – mangle);
     angle = min(angle, 360-angle);
     return angle;



darshak mehta said...

What does the capital letter "D" denotes?

Vinod said...
This comment has been removed by the author.