Sunday, August 23, 2015

[Algorithm][Math] calculate the angle between hour and minute hand


// calculate the angle between hour and minute hand
public int calcAngle( double h, double m)
{
      // validate the input 
      if ( h < 0 || h >12 || m < 0 || m > 60 )
      {
              throw IllegalArgumentInput(“Wrong Input”);
       }
       if ( h==12  ) h = 0;
       if ( m == 60 ) m = 0;
       
       int hour_angle = 30*h + 0.5*m; // 30 degree per hour =  a circle 360 degree / 12 and 1 minute affects 0.5 degree to hour hand
       int minute_angle = 6 * m ;            // 6 degree per minute = a circle 360 degree / 60 

       int angle = abs(hour_angle - minute_angle);
       angle = Math.min(360 -angle, angle);
       return angle;
}

No comments:

Post a Comment