Clear Filters
Clear Filters

If Else problem Valid_date code.

4 views (last 30 days)
Jeremy
Jeremy on 2 May 2024
Commented: Jeremy on 4 May 2024
Write a function called valid_date that takes three positive integer scalar inputs year, month, day. If these three represent a valid date, return a logical true, otherwise false. The name of the output argument is valid. If any of the inputs is not a positive integer scalar, return false as well. Note that every year that is exactly divisible by 4 is a leap year, except for years that are exactly divisible by 100. However, years that are exactly divisible by 400 are also leap years. For example, the year 1900 was not leap year, but the year 2000 was. Note that your solution must not contain any of the date related built-in MATLAB functions.
So ive seen other peoples code and ive been trying to get it on my own but to no luck fails all test but non-scalar and random non-leap years
function [valid] = valid_date(year, month, day);
leap_year = false;
valid = true;
if nargin ~= 3
valid = false;
else
end
if isscalar(year) && isscalar(month) && isscalar(day)
%%if isinteger(year) && isinteger(month) && isinteger(day)
if (year>=0) && (13>month>0) && (32>day>0)
%%fix(year), fix(month), fix(day)
if month == 2 && day == 29
leap_year = true;
elseif rem(year,400) == 0
leap_year = true;
elseif rem(year,4) == 0 && rem(year,100) ~= 0
leap_year = true;
else
leap_year = false;
end
if month ~= 1 || month ~= 3 || month ~= 5 || month ~= 7 || month ~= 9 month ~= 12 && day == 31
valid = false;
elseif month == 2 && day > 29
valid = false;
end
else
valid = false;
end
else
valid = false;
end
  6 Comments
Jeremy
Jeremy on 4 May 2024
im aware that "elseif rem(year,400) ~= 0 || rem(year,4) ~= 0 && rem(year,100) == 0" could just be else valid = false; just now.
Jeremy
Jeremy on 4 May 2024
i just figured out my issue thank you for the help

Sign in to comment.

Answers (1)

Les Beckham
Les Beckham on 2 May 2024
There are several errors. For one thing, you can't combine multiple comparisons into one such as 13>month>0, this must be two conditions: 13>month && month>0. Also, you are setting the leap_year flag but never using it. You should also restore the isinteger tests. Fix up these things and pay attention to the Code Analyzer warnings and you should be able to make it work.

Community Treasure Hunt

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

Start Hunting!