Angle Between Hands of a Clock in C++



In this article, we have values of hours and minutes respectively. Our task is to find a smaller angle formed between the hour and the minute hand.

Wall Clock

Formula to Calculate Angle Between Hour and Minute Hands

The formula for calculating the angle between hour and minute hands is given below:

angle = |30*h - 5.5min|

Example

Here are the examples of calculating the angle between hour and minute hands using the above formula:

Input 1
Time = 12:45, hour = 12, minute = 45
angle = |30*h - 5.5min|
= |30*12 - 5.5*45| = |360 - 247| = 112.5
Output:
112.5

Input 2:
Time = 10:30, hour = 10, minute = 30
angle = |30*h - 5.5min|
= |30*10 - 5.5*30| = |300 - 165| = 135

Output:
135

Calculating Angle Between Hour and Minute Hands in C++

In this example, we have calculated the hour angle and minutes angle and stored their value in hAngle and mAngle. The difference between them is calculated and the minimum angle value is returned using the min() function.

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

double solve(int h, int m)
{
   if (h == 12)
      h = 0;
   if (m == 60)
      m = 0;
   double hAngle = 0.5 * ((60 * h) + m);
   double mAngle = 6 * m;
   double ret = abs(hAngle - mAngle);
   return min(360 - ret, ret);
}
int main()
{
   int hour = 12, min = 30;
   cout << "The given time is= " << hour << ":" << min;
   cout << "\nAngle between them is: " << solve(hour, min);
}

The output of the above code is as follows:

The given time is= 12:30
Angle between them is: 165
Updated on: 2025-06-17T17:58:48+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements