If Else problem Valid_date code.

3 次查看(过去 30 天)
Jeremy
Jeremy 2024-5-2
评论: Jeremy 2024-5-4
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 个评论
Jeremy
Jeremy 2024-5-4
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 2024-5-4
i just figured out my issue thank you for the help

请先登录,再进行评论。

回答(1 个)

Les Beckham
Les Beckham 2024-5-2
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.

类别

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

标签

Community Treasure Hunt

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

Start Hunting!

Translated by