Help Fixing Leap Year Function

2 Ansichten (letzte 30 Tage)
Ainars Cernavskis
Ainars Cernavskis am 6 Jul. 2021
Bearbeitet: Rena Berman am 27 Nov. 2023
So i got a problem with my leap year calculator function which asks user to enter a year and function will tell you if its a leap year or not and ask you if you would like to repeator quit ,but i gota problem and dont really know how to fix it becuase am kinda of a noob.Any help would be great .
Getting erros like:
Line 3: END might be missing,possibly matching WHILE.
Line 9: Parse error at ELSE: usage might be invalid MATLAB syntax
function LeapYears
condition = "yes";
while strcmp(condition,"yes") == 1
year = input (' Enter the year : ');
if mod(year,4) == 0
if mod(year,400) == 0 disp ('true')
elseif mod(year,100) == 0 disp ('false')
else disp ('true')
else disp ('false')
end
condition = input("Would you like to repeat? (yes/no)\n", 's') == "yes";
end
  2 Kommentare
Sam Chak
Sam Chak am 23 Nov. 2023
The original question may be beneficial to people who wish to learn how to test whether a given year is a leap year.
Rena Berman
Rena Berman am 27 Nov. 2023
(Answers Dev) Restored edit

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Jan
Jan am 6 Jul. 2021
Bearbeitet: Jan am 6 Jul. 2021
Use the standard notation and no neat accumulation of commands per line:
function LeapYears
condition = "yes";
while strcmp(condition, "yes") % Optional: == 1
year = input (' Enter the year : ');
if mod(year,4) == 0
if mod(year,400) == 0
disp ('true')
elseif mod(year,100) == 0
disp ('false')
else
disp ('true')
end % <-- this was missing!
else
disp ('false')
end
condition = input("Would you like to repeat? (yes/no)\n", 's');
% The trailing == "yes"; is a bug.
% You do not want [condition] to be TRUE or FALSE, but "yes".
end
A compact test:
if ~mod(year, 4) & (mod(year, 100) | ~mod(year, 400))
disp('leap year')
else
disp('no leap year')
end

Weitere Antworten (1)

Walter Roberson
Walter Roberson am 6 Jul. 2021
function LeapYears
condition = "yes";
while strcmp(condition,"yes") == 1
year = input (' Enter the year : ');
if mod(year,4) == 0
if mod(year,400) == 0
disp ('true')
end
elseif mod(year,100) == 0
disp ('false')
else
Okay, that else matches the elseif which is associated with the if mod(year,4) so it is fine.
disp ('true')
else
But that else does not match anything. To use else, the previous control statement has to be if or elseif, not else
disp ('false')
end
condition = input("Would you like to repeat? (yes/no)\n", 's') == "yes";
end
I would also point put that if a year is NOT divisible by 4 (as needed to reach the elseif) then it cannot be divisible by 100.
if mod(year,400) == 0
disp ('true')
end
Perhaps you wanted an else or elseif there?

Community Treasure Hunt

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

Start Hunting!

Translated by