Help Fixing Leap Year Function

조회 수: 2 (최근 30일)
Ainars Cernavskis
Ainars Cernavskis 2021년 7월 6일
편집: Rena Berman 2023년 11월 27일
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
Sam Chak
Sam Chak 2023년 11월 23일
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 2023년 11월 27일
(Answers Dev) Restored edit

댓글을 달려면 로그인하십시오.

채택된 답변

Jan
Jan 2021년 7월 6일
편집: Jan 2021년 7월 6일
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

추가 답변 (1개)

Walter Roberson
Walter Roberson 2021년 7월 6일
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?

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by