Help Fixing Leap Year Function
조회 수: 2 (최근 30일)
이전 댓글 표시
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
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.
채택된 답변
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
댓글 수: 0
추가 답변 (1개)
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?
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!