The problem is known as a “Clock Angle Problem” where we need to find the angle between the hands (hour & minute) of an analog clock at a particular time.
Solution in C Programming Language.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<inttypes.h>
#include<assert.h>
#define STRING_LENGTH 6
double angle_between_hour_min_hand(char[]);
int main(void) {
uint8_t test;
printf("Enter the number of test cases\n");
scanf("%"SCNu8,&test);
assert(test>0);
while(test--) {
char time_digital[STRING_LENGTH];
printf("Enter the time\n");
scanf("%s",time_digital);
double angle_between_hands_deg = angle_between_hour_min_hand(time_digital);
abs(angle_between_hands_deg) < angle_between_hands_deg ? printf("%0.1f\n",angle_between_hands_deg) : printf("%d\n",abs(angle_between_hands_deg));
}
return 0;
}
double angle_between_hour_min_hand(char time_digital[]) {
uint8_t hr,min;
double hr_angle_deg,min_angle_deg,angle_between_hands_deg;
char*buffer = calloc(sizeof(char),STRING_LENGTH);
if(buffer) {
snprintf(buffer,STRING_LENGTH,"%s",time_digital);
hr = atoi(__strtok_r(buffer,":",&buffer));
min = atoi(__strtok_r(NULL,":",&buffer));
buffer -= strlen(time_digital);
free(buffer);
hr_angle_deg = (double)(30*hr) + (double) (0.5*min);
// printf("hr-angle: %f\n", hr_angle_deg);
min_angle_deg = 6*min;
// printf("min-angle: %f\n", min_angle_deg);
angle_between_hands_deg = (hr_angle_deg > min_angle_deg) ? hr_angle_deg - min_angle_deg : min_angle_deg - hr_angle_deg;
if(angle_between_hands_deg > 180) {
angle_between_hands_deg = 360 - angle_between_hands_deg;
}
}
else fprintf(stderr,"Memory not allocated to the buffer pointer!\n");
return angle_between_hands_deg;
}
Compile the above program in your system, I used Ubuntu 18.04 LTS Bionic Beaver, you can use any system which has a C compiler installed.
gcc -Wall -g clock_angle_sol.c -o clock_angle_sol
./clock_angle_sol
Enter the time in 12-hour or 24 hour i.e (hr:min) format: 12:45
Angle: 112.00 degrees.
Notes:
1. The equation will give you the angle made by hour hand in 12-hour clock.
2. If you want to calculate the angle made by hour hand in a 24-hour clock, then use the following equation:
3. Second hand also contribute to the rotation of the minute hand, but we ignored it because the contribution is insignificant i.e. 1/10 = 0.1.