[英]Time Class Constructor
Here is a implementation that I wrote to add hrs, min and sec in C++ Is there a way to implement this by converting all this to seconds and do a simpler implementation? 这是我编写的在C ++中添加hrs,min和sec的实现。是否可以通过将所有这些转换为秒并执行更简单的实现来实现? For some reason it wouldn't let me add the code in this post :( 由于某种原因,它不会让我在这篇文章中添加代码:(
Thank you 谢谢
将小时,分钟和秒转换为几秒钟是很简单的:
total_seconds = hours*60*60 + minutes*60 + seconds;
Is there a way to implement this by converting all this to seconds and do a simpler implementation? 有没有一种方法可以通过将所有这些转换为秒并执行更简单的方式来实现?
Whichever way you go, you'll need to change the time between seconds and hour/minute/second quite often, so there's not necessarily a huge benefit to using one or the other for storage. 无论您采用哪种方式,都需要经常在秒和时/分/秒之间更改时间,因此使用一个或另一个来存储不一定有很大的好处。 Put another way, seconds-since-midnight is probably nicer, but maybe not worth a rewrite. 换句话说,从午夜开始的秒数可能更好,但可能不值得重写。 For things like +
and -
, if you're not storing just seconds then you can calculate it easily (see Mark's post), do your arithmetic then have a function to convert from seconds back to hour/min/sec to store the result into your data members: 对于+
和-
类的东西,如果您不只是存储秒,那么您可以轻松地进行计算(请参阅Mark的文章),然后进行算术运算,然后将其从秒转换回小时/分钟/秒,以将结果存储到您的数据成员:
hours = seconds_since_midnight / 60 / 60;
minutes = seconds_since_midnight / 60 % 60;
seconds = seconds_since_midnight % 60;
Say you're adding 120 seconds to 23:59:00, you'll get a value past midnight, so you can use "total_seconds % 24 * 60 * 60" to get just the 60 seconds past the following midnight, equivalent to wrapping from "24:01:00" to 00:01:00. 假设您要在23:59:00之前增加120秒,那么您将在午夜之后获得一个值,因此您可以使用“ total_seconds%24 * 60 * 60”来获取下一个午夜之后的60秒,相当于换行从“ 24:01:00”到00:01:00。
(If you want to actually use this, and not just doing this to teach yourself, then consider using the time()
function and associated conversion routines like localtime()
) (如果您想实际使用它,而不仅仅是这样做以自学,那么可以考虑使用time()
函数和相关的转换例程,例如localtime()
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.