Writing a Leap year function without using the leapyr function

16 visualizzazioni (ultimi 30 giorni)
I'm needing a to write a function that takes in a start and end year, and that outputs the leap years in-between those 2 parameters. I feel like I have a good base, but I can't figure out how to include that a year is not a leap year if it is divisible by 100. I have 2 potential ideas as to how to approach the task, but This is what I have so far:
function [] = leapyears(startYear,endYear)
for x=startYear-1:4:endYear-1
fprintf('%i \n', x+1);
if mod(startYear,100)==0
%y=0;
%while y<startYear
%if mod(startYear, 4) == 0 && mod(startYear, 400)==0 && mod(startYear,100)==0
%for x=startYear-1:4:endYear-1
%fprintf('%i \n', x+1);
%end
%y=y+1
%end
end
  2 Commenti
KSSV
KSSV il 21 Feb 2018
You are allowed to use inbuilt function calendar ?
Camila Perez
Camila Perez il 21 Feb 2018
I'm not familiar with the calendar function, is there a way I can go about it without using it?

Accedi per commentare.

Risposta accettata

per isakson
per isakson il 21 Feb 2018
Modificato: per isakson il 21 Feb 2018
Every year that is exactly divisible by four is a leap year, except for years that are exactly divisible by 100, but these centurial years are leap years if they are exactly divisible by 400. For example, the years 1700, 1800, and 1900 are not leap years, but the year 2000 is.[5]
startYear = 1888; endYear = 2003; % Sample data
yy = [startYear:endYear];
is_leap = (mod(yy,4)==0 & not( mod(yy,100)==0 )) | mod(yy,400)==0;
yy(is_leap)
returns
ans =
Columns 1 through 7
1888 1892 1896 1904 1908 1912 1916
Columns 8 through 14
1920 1924 1928 1932 1936 1940 1944
Columns 15 through 21
1948 1952 1956 1960 1964 1968 1972
Columns 22 through 28
1976 1980 1984 1988 1992 1996 2000

Più risposte (0)

Categorie

Scopri di più su Dates and Time in Help Center e File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by