If else condition to determine if a year is a leap year
Mostrar comentarios más antiguos
Hi there. Given a variable Y which stores a year in the 20th century (between 1901 and 2000), write MATLAB code to create a variable Days and assign it a value of 366 if the year is a leap year or a value of 365 otherwise.
1 comentario
Jos (10584)
el 7 de Mzo. de 2014
Homework, not? What did you try yourself?
Respuesta aceptada
Más respuestas (3)
Nitin
el 7 de Mzo. de 2014
0 votos
- The year is evenly divisible by 4;
- If the year can be evenly divided by 100, it is NOT a leap year, unless;
- The year is also evenly divisible by 400. Then it is a leap year.
I have done the first part, I'll leave the rest to you to implement
if mod(year,4)== 0 % use the modulo operator to check for remainder
days == 366
else
days == 365
end
1 comentario
chafah zachary
el 8 de Mzo. de 2014
Ian
el 8 de Sept. de 2016
0 votos
ndays = datenum(Y+1,0,0) - datenum(Y,0,0);
isleap = ndays == 366;
Shikhar Srivastava
el 28 de Mzo. de 2020
Editada: Shikhar Srivastava
el 28 de Mzo. de 2020
0 votos
if(year/4==0 || year/400==0 && ~((year/100==0)))
4 comentarios
"(year/4==0 || year/400==0 && ~((year/100==0)))"
The only year that satisifes the condition is year=0. I doubt that this is very useful.
We can check this approach easily by using array division rather than matrix division:
>> Y = [0;1;2;3;4;5;6;7;8;9];
>> (Y./4==0 | Y./400==0 & ~((Y./100==0))) % only Y=0 -> true
ans =
1
0
0
0
0
0
0
0
0
0
>> Y = 1900:2023;
>> any(Y./4==0 | Y./400==0 & ~((Y./100==0)))
ans = 0
Apparently there were no leap years in the previous century.
Shikhar Srivastava
el 29 de Mzo. de 2020
i m considering years>1000
Rik
el 31 de Mzo. de 2020
Complete code posted as answer in another thread:
%sir, i wrote this code,but it is passing nly random leap yeara,can u point out the mistake.%
function valid=valid_date(year,month,day)
if(year/4==0 || (year/400==0 && ~((year/100==0))))
if(3<=month && month<13 || month==1 && 1<=day && day<32)
valid=true;
elseif(month==2 && 1<=day && day<30)
valid=true;
else
valid=false;
end
else
if(3<=month && month<13 || month==1 && 1<=day && day<32)
valid=true;
elseif (month==2 && 1<=day && day<29)
valid=true;
else
valid=false;
end
end
Rik
el 31 de Mzo. de 2020
You are using division. Consider the year 2004, which was a leap year. What happens for each of your checks?
year/4==0% year/4 is 501, so this returns false
year/400==0% year/400 is 5.01, so this returns false
~(year/100==0)% year/100 is 20.04, so this returns true
%so your if is this:
if false || (false && true)
If you describe it with words, what is the condition to check if a year is a leap year?
Categorías
Más información sobre Data Type Identification en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!