Help Fixing Leap Year Function

3 ビュー (過去 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 Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by