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 commentaires

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.

Connectez-vous pour commenter.

 Réponse acceptée

Rik
Rik le 20 Août 2020
Modifié(e) : Rik le 20 Août 2020
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 commentaires

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.
You're welcome. Feel free to mark my answer as accepted answer or comment with your remaining issues.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Variables dans Centre d'aide et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by