计算日期(使用有限的工具)
我正在尝试计算两个日期之间的差异,作为作业。 唯一的问题是我们不能使用 for while if 循环之外的任何东西......这让我发疯。我尝试为它编写 sudocode ,它看起来很简单,但是当我开始坐下来编码时,当月份开始到来时,我迷失了方向。(不包括闰年)
假设开始日期是 2015 年 7 月 3 日到 2016 年 3 月 5 日。
我最初是要添加天数,直到当前月份结束,并且几乎从天数开始计算所有内容。但当我开始为每个月添加不同的日子时,我有点迷失了。
I'm trying go calculate difference between two dates, for homework.
Only problem is we can't use anything outside of for while if loops.. which is driving me crazy. I tried writing the sudocode for it and it seems simple enough but when I start sitting down and coding I get lost when the months start coming in.(excluding leap years)
Say the start dates is July 3 2015 going to March 5 2016.
I was originaly going to add days until the current month is finish and pretty much calculate everything from days. But I get kinda lost when I start including different days for each month.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
计算出您在该月可以走多远的想法可能是
然后有一个 days_in_month 函数,该函数使用一些 if 语句返回。如果你有一点谷歌,我记得看到了一些很好的语句来有效地解决这个问题 - 如果你需要包括闰年,你显然需要将年份传递给 days_in_month 函数。
显然,您需要在上面的循环中嵌套一些其他循环。
希望这有帮助,祝你好运。
An idea to work out how far you can go in that month might be
Then have a days_in_month function, that returns, using a few if statements. If you have a bit of google I remember seeing a few good statements to efficiently work this out - if you need to include leap years you'll obviously need to pass the year to the days_in_month function.
Oviously you'll need the above loop nested some other ones.
Hope this helps, good luck.
步骤 1:编写一个函数将日期转换为“自纪元以来的天数”,其中考虑了闰年等因素。纪元可能是“1/1/1970”。只需使用查找表就很容易了 - 一个用于“前几年的天数”,包括闰年标志,另一个用于非闰年的“前几个月的天数”(如果上一个表中的闰年标志设置并且该月份是二月之后,您添加一天)。然后添加“前几年的天数”、“前几个月的天数”和该月的日期以获得“自 epoc 以来的天数”。
步骤 2:将两个日期转换为“自 epoc 以来的天数”整数并相减。
注意:讲师可能希望您使用计算而不是查找表。在这种情况下,请使用查找表使其正常工作,然后一次更换一个查找表。
Step 1: Write a function to convert a date into a "day number since epoc", which takes into account things like leap years, etc. The epoc could probably be "1/1/1970". It'd be easy to just use lookup tables - one for "days in previous years" that includes a leap year flag and one for "days in previous months" for non-leap years (where if the leap year flag from the previous table is set and the month is after February, you add a day). Then you'd add "days in previous years", "days in previous months" and the day of the month to get "day number since epoc".
Step 2: Convert both dates into "day number since epoc" integers and subtract.
Note: The lecturer might expect you to use calculations rather than using lookup tables. In this case, use lookup tables to get it working, then replace the lookup tables one at a time.