205k views
4 votes
Write a program to calculate the number of seconds since midnight. For example, suppose the time is 1:02:05 AM. Since there are 3600 seconds per hour and 60 seconds per minutes, it has been 3725 seconds since midnight (3600 * 1 + 2 * 60 + 5 = 3725). The program asks the user to enter 4 pieces of information: hour, minute, second, and AM/PM. The program will calculate and display the number of seconds since midnight. [Hint: be very careful when the hour is 12].

User Nere
by
5.7k points

1 Answer

4 votes

Answer:

// here is code in c++.

#include <bits/stdc++.h>

using namespace std;

int main()

{

// variables

int hour,min,sec,tot_sec;

string str,s="AM";

cout<<"enter number of hours:";

// read hour

cin>>hour;

cout<<"enter number of minutes:";

// read minute

cin>>min;

cout<<"enter number of seconds:";

// read seconds

cin>>sec;

cout<<"Enter AM or PM:";

// read AM or PM

cin>>str;

if((str.compare(s) == 0 )&& hour==12)

{

hour=0;

}

// calculate total seconds

tot_sec=hour*3600+min*60+sec;

// print the output

cout<<"total seconds since midnight is : "<<tot_sec<<endl;

return 0;

}

Step-by-step explanation:

Read the value of hour, minute, second and string "AM" or "PM" from user.

Then if string is equal to "AM" then make hour=0.Then multiply hour with

3600, minute with 60 and add them with second.It will give the total seconds

from midnight.

Output:

enter number of hours:12

enter number of minutes:46

enter number of seconds:23

Enter AM or PM:AM

total seconds since midnight is: 2783

User Marc Balmer
by
5.0k points