Use Switch function to find day of year
27 views (last 30 days)
Show older comments
Write an executable script file (m-file) that takes no inputs and calculates the day of year associated with any given month, day, and year. The program should be able to check to see if the data entered by the user is valid. If the inputs are invalid, the program should tell the user what is wrong and quit. The year should be a number greater than zero, the month should be a number between 1 and 12, and the day should be a number between 1 and a maximum that depends on the month selected. Use a switchconstruct to implement the bounds checking performed on the day. Make sure to include leap years.
I am stuck, it only returns a number 16
month = input('Enter month (1-12):');
day = input('Enter day(1-31):');
year = input('Enter year(greater than zero xxxx):');
if mod(year,400) == 0
leap_day = 1;
elseif mod(year,100) == 0
leap_day = 0;
elseif mod(year,4) == 0
leap_day = 1;
else
leap_day = 0;
end
switch('day')
case{1}
day_of_year=day
case{2}
day_of_year=total(day,leap_day,31)
case{3}
day_of_year={day + 28 + leap_day+31}
case{4}
day_of_year={day + 28 + leap_day+31+30}
case{5}
day_of_year={day + 28 + leap_day+31+30+31}
case{6}
day_of_year={day + 28 + leap_day+31+30+31+30}
case{7}
day_of_year={day + 28 + leap_day+31+30+31+30+31}
case{8}
day_of_year={day + 28 + leap_day+31+30+31+30+31+31}
case{9}
day_of_year={day + 28 + leap_day+31+30+31+30+31+31+30}
case{10}
day_of_year={day + 28 + leap_day+31+30+31+30+31+31+30+31}
case{11}
day_of_year={day + 28 + leap_day+31+30+31+30+31+31+30+31+30}
case{12}
day_of_year={day + 28 + leap_day+31+30+31+30+31+31+30+31+30+31}
otherwise
fprintf('invalid entry');
end
4 Comments
Geoff Hayes
on 9 Apr 2020
I think by Use a switchconstruct to implement the bounds checking performed on the day., the intention is to make sure that the day entered is valid for the month (since that is the only bounds checking that you will do). For example,
switch (month)
case 1
if day < 1 || day > 31
error(sprintf('Invalid day (%d) for month (%d)\n', day, month);
end
case 2
if day < 1 || (leap_day == 1 && day > 29) || (leap_day == 0 && day > 28)
error(sprintf('Invalid day (%d) for month (%d)\n', day, month);
end
% etc.
end
Answers (0)
See Also
Categories
Find more on Language Fundamentals in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!