Write a function called valid_date that takes three positive integer scalar inputs year, month, day. If these three represent a valid date, return a logical true, otherwise false. The name of the output argument is valid. If any of the inputs is not

hey,
people
The code the I wrote is giving the correct output for some dates but it is not giving the correct output for the date valid_date(1900,2,29).
And i even tried to input non-scalar values and the Run function command is showing valid=0 for non-scalar value then why is it not accepting the answer

2 件のコメント

Geoff Hayes
Geoff Hayes 2020 年 8 月 20 日
Amit - rather than posting a screen shot of the code, attach it instead so that we can run through it ourselves to help you understand what the problem might be. For the input date of 1900-2-29, I would use the MATLAB debugger to step through the code to see where the valid flag is being set to false and hopefully correct the error at that line. As for the non-scalar input values, please provide some examples of what you mean by this.
ok . I will try and use the debugger first then if the problem persists i would ask again.

サインインしてコメントする。

 採用された回答

Rik
Rik 2020 年 8 月 20 日
編集済み: Rik 2020 年 8 月 20 日
There are two things I notice in your code:
  1. You don't test anywhere whether the input is a scalar or a vector/array.
  2. Your leap year detector will mark every year that is a multiple of 4 as a leap year, without taking into account the exceptions.
For that second one I recommend writing it first separately. Test it for 1900, 2000, 2004, and 2005.
clc
for year=[1900 2000 2004 2005]
%your current test:
if ( mod(year,4)==0 ) || ( mod(year,400)==0 && mod(year,100)==0 )
txt='a';
else
txt='not a';
end
fprintf('%d is %s leap year\n',year,txt)
end

2 件のコメント

ok , I found the mistake I was doing
the "for" loop for leap year dhouls have been the below one
for ( mod(year,4)==0 ) && ( mod(year,400)==0 || mod(year,100)~=0 )
it worked.
Rik
Rik 2020 年 8 月 21 日
You're welcome. Feel free to mark my answer as accepted answer or comment with your remaining issues.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeVariables についてさらに検索

タグ

質問済み:

2020 年 8 月 20 日

コメント済み:

Rik
2020 年 8 月 21 日

Community Treasure Hunt

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

Start Hunting!

Translated by