Program to determine the angle between the hands of a clock

Determine the included angle between the hands of a clock if the time of the day is given.

Last Reviewed and Updated on June 24, 2017
Posted by Parveen(Hoven),
Aptitude Trainer and Software Developer

Advertisement

Program to determine the angle between the hands of a clock.

Ask the user to enter two int numbers - h for hours, and m for minutes. Write a program to determine the angle between the hands of a clock.

Step 1: First create a function that takes two int type of arguments - hour and minute.

float getAngle(int h, int m)
{
    // first calculate angle for hours clock 
    // The angle is measured in degrees 
    // from the mark of number 12 clockwise.
    
    // how many minutes have elapsed?
    int totalMinutes = 60 * h + m;
 
    // hours clock travels (360 / 12 ) / 60 
    // = 0.5 degrees in one minute. total degrees?
    float angleHours = totalMinutes * 0.5f;
 
    // next take the minutes hand
    // it travels 360 degrees in 60 minutes
    // so in one minute it travels = 
    // 360 / 60 = 6 degrees. total angle?
    float angleMinutes = m * 6.0f;
 
    // the difference 
    float angle = angleMinutes - angleHours;
 
    // if it is negative, make absolute
    if(angle < 0)
    {
        angle *= -1;
    }
 
    // if it is reflex, correct it
    if(angle > 180)
    {
        angle -= 180;
    }
 
    return angle;
}

Step 2: Call the above function from your main.

int main()
{
    int h, m;
 
    cout << "Enter hours[0-11]: ";
 
    cin >> h;
 
    cout << "Enter minutes[0-59]: ";
 
    cin >> m;
 
    if(h > 11 || m > 59 || h < 0 || m < 0)
    {
        cout << "Bad input" << endl; 
 
        return 0;
    }
    
    cout << "Angle is: " << getAngle(h, m) << endl;
 
    return 0;
}

My C/C++ Videos on Youtube

Here is the complete playlist for video lectures and tutorials for the absolute beginners. The language has been kept simple so that anybody can easily understand them. I have avoided complex jargon in these videos.



Creative Commons License
This Blog Post/Article "Program to determine the angle between the hands of a clock" by Parveen (Hoven) is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
Updated on 2017-06-24.


Advertisement