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)
4 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponses (1)
per isakson
le 14 Déc 2018
Modifié(e) : per isakson
le 14 Déc 2018
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 commentaires
per isakson
le 14 Déc 2018
Modifié(e) : per isakson
le 14 Déc 2018
Thus replace
dd = [];
by
dd = -1;
and delete the disp-statements if you don't want the text output in the command window
Voir également
Catégories
En savoir plus sur Logical dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!