【发布时间】:2021-05-15 23:30:33
【问题描述】:
这里的问题是在不使用原生 Matlab 日期函数的情况下查找提供的日期是否有效。我希望有人能在这里指出我的错误。当我提交时,我还在 Matlab 学习工具中收到“在调用 valid_date 期间未分配输出参数 valid(可能还有其他)”错误。
function valid = valid_date(year,month,day)
if nargin~=3
valid = false;
elseif ~isscalar(year)||year<1||year~=fix(year)
valid = false;
return
elseif ~isscalar(month)||month<1||month~=fix(month)
valid = false;
return
elseif ~isscalar(day)||day<1||day~=fix(day)
valid = false;
return
elseif month>12 || day > 31
valid = false;
end
if ((mod(year,4)==0 && mod(year,100)~=0) || mod(year,400)==0)
leapdata=1;
else
leapdata=0;
end
%the below if statements are used to define the months. Some months have
%31 days and others have 30 days, while February has only 28 days and 29 on
%leap years. this is checked in the below code.
% I feel the below code is where the error is.
if ismember (month, [1 3 5 7 8 10 12])
ismember (day, (1:31))
return
elseif ismember( month, [4 6 9 11])
ismember (day, (1:30))
return
end
if month == 2
if leapdata==1
ismember (day, (1:29))
return
elseif leapdata==0
ismember (day, (1:28))
return
else
valid = false;
end
end
【问题讨论】:
-
请从基础开始:mathworks.com/help/matlab/matlab_prog/… — 通过反复试验学习编程没有必要令人沮丧,跳过基础知识会让你走上痛苦的道路。
-
您忘记在多次退货中分配
valid值。另外,我建议您发布整个错误,以便更清楚地了解错误发生的位置 -
@CrisLuengo,这实际上是基础课程中的一个问题。的确,通过反复试验来做到这一点非常令人沮丧,周六我被困在这个问题上将近 9 个小时:/