0

For one of my college classes using C++, we have to implement a class that creates time objects and that can do different arithmetic functions (+, -, -=, +=, etc...) between two different times.

My teacher told us that for this lab, the different components of calendar time (hours, minutes, seconds) are type unsigned int.

We have an issue when subtracting between different times. Since the type is unsigned int, if t1 < t2, then t1 - t2 would result in large number by cyclicity of unsigned int.

How would one go about solving this problem?

Edit: An example would be let's say t1 = 00:00:00 and t2 = 00:00:01. If we were to do t1 - t2, we are supposed to have 23:59:59 as the final answer

  • Throw an error if t1 < t2. Or if you want a result `t1 < t2 ? t2 - t1 : t1 - t2` – Robin Dillen Jan 17 '22 at 16:40
  • Hi, thank you for responding. The issue is if let's say t1 = 00:00:00 and t2 = 00:00:01 by doing t1 - t2, we are supposed to land at 23:59:59. By doing what you proposed our final answer would be 00:00:01 –  itsthea Jan 17 '22 at 16:46
  • @itsthea: Then... do that. Test to see if it's greater, and do different math if it is. What's the problem? – Nicol Bolas Jan 17 '22 at 16:53
  • Take a look at [modular arithmetic](https://en.wikipedia.org/wiki/Modular_arithmetic) and the modulo operator in C++ – eike Jan 17 '22 at 16:55

1 Answers1

0

You would fix this by first substracting t2 from t1 by doing:

int temp_hours = t2.hours - t1.hours

For every value(hours, minutes...). Then set t1 to 24:00:00 and do normal substraction with your temp values.

PS: to avoid code duplication i imagine recursion could be quite nice

Or as said in the comments you can use modular arithmic, although the python version should be used, so when I use modulo I mean this modulo:

int temp_hours = t1.hours - t2.hours
// same as before, but after the substractions make sure to also decrease the rest for example 00:00:00 - 00:00:01 -> -1:-1:-1

then take the (python) modulo:

t1.hours = temp_hours % 24
t1.minutes= temp_minutes % 60
// ...
Robin Dillen
  • 704
  • 5
  • 11