Find out if number is divisible by x
Afficher commentaires plus anciens
I'm trying to write a function that determines if the input is a valid date, and for that I need a function that will tell me if an input number is divisible by 4 and at the same time not divisible by 100 (this has to do with leap years but I'm not supposed to use the special function for that). This is what I came up with but I can already see that it's not correct. In non-code language, I would like it to be something like "If divisors(year) contains the number 4 and does not contain the number 100, display the following..." but I did not know how to do this.
(This is just the part of code I'm struggling with, I didn't paste everything because it was quite a lot.)
Any tips on how I should fix it would be much appreciated!
function valid = valid_date(year,month,day)
if divisors(year) = 4 ~ 100
.
.
.
.
.
end
1 commentaire
James Tursa
le 8 Avr 2019
You're also going to need a divisible by 400 test.
Réponse acceptée
Plus de réponses (2)
Steven Lord
le 8 Avr 2019
1 vote
Take a look at the rem and mod functions.
5 commentaires
James Tursa
le 8 Avr 2019
Rose's answer moved here:
I actually did but I understood that they return the remaining number after division. Do they actually simply tell if a number is divisible by something, just a true/false answer?
James Tursa
le 8 Avr 2019
Modifié(e) : James Tursa
le 8 Avr 2019
@Rose: Yes, if the remainder is 0, then the numbers are exactly divisible. So you can use it for that test.
Steven Lord
le 8 Avr 2019
Consider mod(15, 3) and mod(16, 3). How would you use those answers to tell that 15 is divisible by 3 and 16 is not?
RP
le 8 Avr 2019
James Tursa
le 8 Avr 2019
The = is an assignment operator in MATLAB. The == is the equality test operator. So
if mod(x,y) == 0
Uriel Serrato
le 23 Juil 2020
1 vote
function valid=valid_date(year,month,day)
if isscalar(year)==false || isscalar(month)==false || isscalar(day)==false
valid=false ;
return
end
if ((1<= month) && (month<= 12)) && ((1<= day) && (day<= 31)) && (month==1||month==3||month==5||month==7||month==8||month==10||month==12)
valid=true;
elseif ((1<= month) && (month<= 12)) && ((1<= day) && (day<= 30)) && ((month==4||month==6||month==9||month==11))
valid=true;
elseif ((1<= month) && (month<= 12)) && ((1<= day) && (day<= 29)) && (month==2)&& (mod(year,4)==0 || mod(year,400)==0) && ~mod(year,100)==0
valid= true;
elseif ((1<= month) && (month<= 12)) && ((1<= day) && (day<= 28)) && (month==2)
valid=true;
else
valid=false;
end
Catégories
En savoir plus sur Dates and Time dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!