Angle Between Clock Hands
National Olympiad — National round
Submission name: clock.cpp
Problem summary
Find the smaller angle between continuously moving hour and minute hands at the specified time.
Input
A time in HH:MM format.
Output
Angle in degrees with exactly three digits after the decimal point.
Constraints
01 ≤ HH ≤ 12; 00 ≤ MM ≤ 59.
Worked example
An independently prepared example for this explanation.
Input
03:30
Output
75.000
Solution analysis
- The minute hand is at 6M degrees; the hour hand is at 30(H mod 12)+M/2 degrees.
- Take their absolute difference and the smaller of it and 360 minus it.
Why it works
Both positions follow constant angular velocities; complementary arcs determine the two possible angles.
Watch out. The hour hand moves between hour marks.
Commented C++17 solution
An independently written complete program with standard headers.
// Key idea: Both positions follow constant angular velocities; complementary arcs determine the two
// possible angles.
#include<iostream>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<cstdlib>
using namespace std;
int main(){
int h,m;
char colon;
cin>>h>>colon>>m;
double d=abs(30.0*(h%12)+0.5*m-6*m);
cout<<fixed<<setprecision(3)<<min(d,360-d)<<'\n';
}