Hello everyone, I am having trouble getting this function to work properly. Can someone please point me in the right direction.
I was given a class DigitalTime and i need to add a function that will compute the difference of two times. I tried to do it the same way as in the rational number problem but that didn't work.
the times are in 24hr notation
here is the block from main that calls the function
1 2 3 4 5
DigitalTime current(5, 45), previous(2, 30);
int hours, minutes;
current.interval_since(previous, hours, minutes);
cout << "the time interval between " << previous << " and " << current << endl;
cout << "is " << hours << " hours and " << minutes << " minutes " << endl;
here is the definition so far I know its bad (I was given the function I just need to figure out the body)
Well, the function doesn't need to return anything, since it is declared as void. The result values are simply stored in the two parameter variables: hours_in_interval and minutes_in_interval.
What I would do is to calculate in minutes the difference between the time stored in the current object, and the time passed in the parameter a_previous_time, and then convert back to hours and minutes at the end.
void DigitalTime::interval_since( const DigitalTime& a_previous_time,
int& hours_in_interval, int& minutes_in_interval) const
{
constint total_minutes = minutes_since_midnight() - a_previous_time.minutes_since_midnight() ;
// take it up from there
}
i get the expected "3 hours and 15 minuets". But it only works for times of the same day. If I change current to (1, 45) and leave previous alone it returns a negative 1. That doesn't make since you cant have negative time. but for my purpose it will work. I was thinking I might be able to add an if statement to increase the interval by 1 day if current < previous. but not sure
I'm not ether. I was given everything but the body of the function and was just looking for the easiest way to make it work. Unfortunatly when it comes to code ive found out that what seems like the easy way usually just leads to more problems. like if and else patches
but I wanted to thank you for your help chervil, you have answered almost every question I have posted on this site, in terms I can understand. I would probably be failing if it weren't for you. So thank you for your help.
It's just that in this case I do think the earlier advice either from JLBorges or myself appears not to have been heeded. Of course it is only a suggestion which you are free to ignore, but my feeling is that doing a single subtraction in terms of minutes (rather than separate subtractions for hours and minutes) will work out simpler in the long run.