【问题标题】:Calculate time difference in C++(hours, minutes, seconds) with type unsigned int使用 unsigned int 类型计算 C++(小时、分钟、秒)中的时间差
【发布时间】:2022-01-17 16:39:08
【问题描述】:

对于我的一个使用 C++ 的大学课程,我们必须实现一个创建时间对象的类,该类可以在两个不同的时间之间执行不同的算术函数(+、-、-=、+= 等...)。

我的老师告诉我们,对于这个实验,日历时间的不同组成部分(小时、分钟、秒)是 unsigned int 类型。

我们在不同时间之间进行减法时遇到问题。由于类型是unsigned int,如果t1

如何解决这个问题?

编辑:例如,假设 t1 = 00:00:00 和 t2 = 00:00:01。如果我们做 t1 - t2,我们应该有 23:59:59 作为最终答案

【问题讨论】:

  • 如果 t1 t1 < t2 ? t2 - t1 : t1 - t2
  • 您好,感谢您的回复。问题是如果假设 t1 = 00:00:00 和 t2 = 00:00:01 通过执行 t1 - t2,我们应该在 23:59:59 降落。按照您的建议,我们的最终答案将是 00:00:01
  • @itsthea:那么……就这样吧。测试它是否更大,如果是,则进行不同的数学运算。有什么问题?
  • 看看modular arithmetic和C++中的模运算符

标签: c++ time unsigned unsigned-integer


【解决方案1】:

您可以通过以下方式首先从 t1 中减去 t2 来解决此问题:

int temp_hours = t2.hours - t1.hours

对于每个值(小时、分钟...)。然后将 t1 设置为 24:00:00 并使用您的温度值进行正常减法。

PS:为了避免代码重复,我想递归可能会很好

或者如 cmets 中所说,您可以使用模数运算,虽然应该使用 python 版本,所以当我使用模数时,我的意思是 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

然后取 (python) 模数:

t1.hours = temp_hours % 24
t1.minutes= temp_minutes % 60
// ...

【讨论】:

    猜你喜欢
    • 2020-01-03
    • 1970-01-01
    • 1970-01-01
    • 2011-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多