1. Write a C++ program that takes two different train departure times (where 0 i
ID: 3877197 • Letter: 1
Question
1. Write a C++ program that takes two different train departure times (where 0 is midnight,0700 is 7:00 a.m., 1314 is 14 minutes oast 1:00 p.m., and 2200 is 10 p.m) and prints the difference between the two times in hours and minutes. Assume both times are on the same date and that both times are valid. For example,1099 is not a valid time because the last two digits are minutes which should be in the range of 00 through 59.2401 is not valid because the hours (the first two digits must be in the range of 0 through 23 inclusive. For example, if train A departs at:1255 and train B departs at:1305 the difference would be 0 hours and 10 minutes. One dialogue should look like this, but run your program several times for several test cases.
Train A departs at: 1285
Train B departs at:1305
Difference: 0 hours and 10 minutes
Explanation / Answer
The code is
#include <iostream>
using namespace std;
#include <cassert>
extern int timediff(int t1, int t2);
int timediff(int t1, int t2)
{
assert(t1 >= 0 && t1 <= 2400);
assert(t2 >= 0 && t2 <= 2400);
assert(t1 % 100 < 60 && t2 % 100 < 60);
int mins1 = (t1 / 100) * 60 + (t1 % 100);
int mins2 = (t2 / 100) * 60 + (t2 % 100);
return(mins2 - mins1);
}
int main()
{
int t1,t2;
cout<<"Train A departs at: ";
cin>>t1;
cout<<" Train B departs at: ";
cin>>t2;
int mins,hours;
//t1=1250,t2=1305;
mins=timediff(t1,t2);
hours=mins/60;
mins-=hours*60;
cout<<hours<<" hours and "<<mins<<" minutes ";
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.