Write and Test 3 functions to convert month number to month name
1 次查看(过去 30 天)
显示 更早的评论
Write and test 3 MATLAB functions month2nameA, month2nameB, month2nameC
to convert the numerical month of the year into the name of that month.
Assume 1=January to 12=December. and use a set of only "if" statements for month2nameA use a set of "elseif" statements for month2nameB use a "switch" statement for month2nameC.
I then have to write a test script called TestMonths which uses a for loop, to display all
the names from each function month2nameA, month2nameB, month2nameC.
The name of each month should appear together 3 times (I.e. once for each
function, then move to the next month in the list/loop).
My first function i think is something along the lines of:
function [months] = month2nameA (MonthNumber)
months = {'January', 'February', 'March', 'April', 'May', 'June', ...
'July', 'August', 'September', 'October', 'November', 'December'};
monthNumber = 3;
if monthNumber > 1 && monthNumber < length(months)
theMonth = months{monthNumber}
end
My second function is:
function [months] = month2nameB (MonthNumber)
months = {'January', 'February', 'March', 'April', 'May', 'June', ...
'July', 'August', 'September', 'October', 'November', 'December'};
monthNumber = ;
if monthNumber > 1 && monthNumber < length(months)
theMonth = months{monthNumber};
elseif monthNumber == 1
theMonth = 'January';
elseif monthNumber == 12
theMonth = 'December';
else
theMonth = 'Invalid Month Number'
end
end
My 3rd function is
function [months] = month2namec (MonthNumber)
switch (monthNumber);
case {1,2,3,4,5,6,7,8,9,10,11,12};
fprintf('You picked month %s\n', months{'January', 'February'...
'March', 'April', 'May', 'June', 'July', 'August', 'September'...
'October', 'November', 'December'});
otherwise
fprintf('Invalid month number of %d', monthNumber);
end
end
I know none of these are exactly correct but could anyone help where I am going wrong in these, and how I would construct these functions correctly to test them and then be able to put them in the 'for' loop.
Thank you.
0 个评论
回答(1 个)
Star Strider
2014-11-20
You need to correct the logic in your if statement to allow January and December:
monthNumber >= 1 && monthNumber <= length(months)
replacing ‘>’ with ‘>=’ and ‘<’ with ‘<=’ respectively. The others I didn’t test.
2 个评论
Star Strider
2014-11-20
My pleasure!
You need to be sure to include that logic in your first two functions. The third uses a different approach, so it’s safe.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Testing Frameworks 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!