MATLAB Cody Coursework Help

2 次查看(过去 30 天)
Ian Connelly
Ian Connelly 2016-3-2
Hey, So I'm working on some MATLAB homework where I am given two strings in "HH:MM:SS" format and I need to find the difference of the two strings in minutes. The code that I have written passes a majority of the tests in Cody Coursework, but for some reason can't pass the third test. Does anyone have any suggestions on where my code is incorrect?
function elapsed = elapsed_time(d1,d2)
D1 = datevec(d1, 'HH MM SS');
D2 = datevec(d2, 'HH MM SS');
sum1 = (D1(4)*60) + D1(5) + (D1(6)*0.016667);
sum2 = (D2(4)*60) + D2(5) + (D2(6)*0.016667);
elapsed = (abs(sum1-sum2));
end
Any help would be nice, thanks in advance

回答(1 个)

Guillaume
Guillaume 2016-3-2
I'd use datetime instead of datevec. It makes this sort of calculations much easier:
elapsed = minutes(datetime(d2, 'InputFormat', 'HH mm ss') - ...
datetime(d1, 'InputFormat', 'HH mm ss')); %note the difference in format string
As we don't know what your 3rd test is, we can only speculate on the cause of failure. I would suspect it's because 0.016667 is only a crude approximation of 1/60, and for some values the difference is enough to put you over the accuracy threshold required by the test.
You gain nothing by using a multiplication by 0.016667 and it actually makes your code more obscure as the reader now has to check that 0.016667 is a correct approximation for 1/60, so what don't you write it as a division. Makes a lot more sense to me:
m = d(4)*60 + d(5) + d(6)/60; %is a lot more accurate and it's that you're converting seconds into minutes
  1 个评论
Steven Lord
Steven Lord 2016-3-2
Alternately, convert the two times into a number of seconds (so there's no division involved in the conversions.) Compute the difference between the two times in seconds. Finally convert the difference in seconds into minutes (so there's just one division.)

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 MATLAB 的更多信息

标签

尚未输入任何标签。

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by