How to find the Angle between the hour hand and minute hand in C++

In this tutorial, we will learn to get or find the angle between the hour hand and minute hand in C++. Also, we say this problem as analog clock angle problem where we have to find the angle between the hands of a clock at a given time.

For Example:

  • Given Input: h = 6:00, m = 60.00
  • Output: 180 degree

Now, we will take 12:00  where h = 12 and m = 0 as a reference.

Hence, these are the following steps.

  •  Now, we will get the angle between the hour hand and reference time 12:00 whereas time will be in h hours and m minutes.
  • Then, we will get the angle between the minute hand and reference time 12:00.
  •  Finally, the difference between these two angles is the angle between the minute hand and hour hand.

So, here the question arises, how to get the angle with respect to 12:00?

How to get the angle with respect to 12:00?

  • As we know, the minute hand will move by 360 degrees in 60 minutes or we can say 6 degrees in one minute.
  • And the hour hand will move by 360 degrees in 12 hours or we can say 0.5 degrees in one minute.
  • According to this, the minute hand will move by (h*60 + m)*6 and hour hand will move by (h*60 + m)*0.5.

You may also like:
Convert 24-hour format to 12-hour format in C++

 

 Angle between the hour hand and minute hand

Hence, below is the implementation of the above approach.

 #include<iostream>
#include <bits/stdc++.h> 
using namespace std; 

 //find minimum of two integers 
int min(int a, int b) 
{ 
  return (a < b)? a:b; 
  
} 

int calculateangle(double H, double M) 
{ 
  // validate 
  if (H <0 || M < 0 || H >12 || M > 60) 
    cout<<"input is wrong "; 

  if (H == 12) 
      H = 0; 
  if (M == 60) 
      M = 0; 

  // Calculate the angles 
  int hourangle = 0.5 * (H * 60 + M); 
  int minangle = 6 * M; 

  // Find the difference  
  int angdiff = abs(hourangle - minangle); 

  // Return the smaller angle of two possible angles 
  angdiff = min(360 - angdiff, angdiff); 

  return angdiff; 
} 


int main() 
{ 
  cout << calculateangle(6, 60) << endl; 
  cout << calculateangle(7, 30) << endl; 
  return 0; 
} 


Output Explanation:

OUTPUT:

180
45

You may also read:

Leave a Reply

Your email address will not be published. Required fields are marked *