I want an if-else statement to check whether the a part of the input is a decimal or not? The following program gave an error for input (2.3, 4, 5, 6)
3 次查看(过去 30 天)
显示 更早的评论
function dd = day_diff(m1, d1, m2, d2)
m(1:12) = [31 28 31 30 31 30 31 31 30 31 30 31];
if m1>=13 && m2>=13 && d1>=32 && d2>=32
dd=-1;
elseif (m1==2 && d1>=29) || (m2==2 && d2>=29)
dd=-1;
elseif (m1==4 && d1>=31) || (m1==6 && d1>=31) || (m1==9 && d1>=31) || (m1==11 && d1>=31)
dd=-1;
elseif (m1==1 && d1>=32) || (m1==3 && d1>=32) || (m1==5 && d1>=32) || (m1==7 && d1>=32) || (m1==8 && d1>=32) || (m1==10 && d1>=32) || (m1==12 && d1>=32)
dd=-1;
elseif (m2==4 && d2>=31) || (m2==6 && d2>=31) || (m2==9 && d2>=31) || (m2==11 && d2>=31)
dd=-1;
elseif (m2==1 && d2>=32) || (m2==3 && d2>=32) || (m2==5 && d2>=32) || (m2==7 && d2>=32) || (m2==8 && d2>=32) || (m2==10 && d2>=32) || (m2==12 && d2>=32)
dd=-1;
elseif (m1<=0 || d1<=0) || (m2<=0 || d2<=0)
dd=-1;
elseif m1<=12 && m2<=12 && d1<=31 && d2<=31
dd=abs(sum(m(m1:m2)) - d1 - (m(m2)-d2));
end
end
0 个评论
回答(1 个)
per isakson
2018-12-14
编辑:per isakson
2018-12-14
I get a warning (not an error) and that's because 2.3 isn't an integer.
>> day_diff( 2.3, 4, 5, 6 );
Warning: Integer operands are required for colon operator when used as index.
> In day_diff (line 19)
where line 19 is
dd=abs(sum(m(m1:m2)) - d1 - (m(m2)-d2));
Add
inarg = [m1,d1,m2,d2];
if all(inarg==round(inarg))
disp('all input arguments are whole numbers')
else
disp('one or more of the input arguments are NOT whole numbers')
dd = [];
return
end
in the beginning of the function.
2 个评论
per isakson
2018-12-14
编辑:per isakson
2018-12-14
Thus replace
dd = [];
by
dd = -1;
and delete the disp-statements if you don't want the text output in the command window
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Symbolic Math Toolbox 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!