Monday, May 24, 2010

C++ "No Full answers only Hints and links"?

I have to write an application, that reads two time values (times are represented by two int numbers: hours and minutes). Then the program finds out which time is the later time. After that it calculates the time difference between these times. Finally the program displays the smaller (earlier) time and the time difference (duration) in the format: • starting time was 11:22 • duration was 1:04








int main(void) •{ • Time time1, time2, duration; • time1.read("Enter time 1"); • time2.read("Enter time 2"); • if (time1.lessThan(time2)) { • duration = time2.subtract(time1); • cout %26lt;%26lt; "Starting time was "; • time1.display(); • } • else { • duration = time1.subtract(time2); • cout %26lt;%26lt; "Starting time was "; • time2.display(); • } • cout %26lt;%26lt; "Duration was "; • duration.display(); •}














As can be seen from the main function, Time has the following member functions: •read that is used to read time (minutes and hours) from the keyboard. •lessThan that is used to compare two times. •subtract that is used to calculate time difference between two times. •display that is used to display time in the format hh:mm.

C++ "No Full answers only Hints and links"?
For nicer code, and to take advantage of C++ features, you could overload operators for your Time class: operator-, operator%26gt;, operator%26lt;, operator==, ostream operator%26lt;%26lt;, etc. You may not want to get too sidetracked on the niceties, however, because there's some interesting code to be written for your less than and subtraction operations.





Hints:


If the Time class' time attribute is a struct { hour, min }, you can use memcmp for your less than operation. Beware that this only works if you're running on a big-endian architecture. If little-endian, have Time maintain a struct with swapped bytes, and use that for your comparisons.





Code the subtraction operation as if you were doing it by hand on paper. E.g., for 11:22 - 00:30, since 30 %26gt; 22 you need to borrow 1 hour. So you have 10:82 - 00:30 = 10:52.





Decide if you want your Time class to be able to represent negative time. I would suggest a 'sign' attribute. If you have to compute 00:30 - 11:22, you use your less than operator to see that the minuend is less than the subtrahend. Swap minuend and subtrahend, compute 11:22 - 00:30 as before, and set Time's sign to negative.





There's some good stuff to be done here. Have fun!


No comments:

Post a Comment