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