views:

44

answers:

1

In my programming class, we have

struct Time {
    int hours, min, sec;
}

We are to create a method to compute the difference between two times:

Time *timeDiff(const Time *t1, const Time *t2)

I thought I could create the time difference by getting everything in seconds, and then subtracting the two values, but it seems like extra work to do something like

long hour1 = t1->hours;
long min1 = t1->min;
long sec1 = t1->sec;

And then using these values to get the time in seconds, do something similar for the second time, and then subtract. Any thoughts? Thanks!

+3  A: 

The way you've described it sounds exactly right. I might do something like

int sec = t1->sec + 60*(t1->min + 60*t1->hours);

Then similarly for t2, then subtract one from the other and break the result down into minutes and hours.

Graeme Perrow
Agreed that this is the most general way - and easily expandable to include days. Create two functions - one to convert struct Time to secs and one to do the reverse.
Dipstick