Info

This question is closed. Reopen it to edit or answer.

Why is my code displaying two messages instead of one?

3 views (last 30 days)
if BirthM == 1
fprintf (fileID,'\n you are %d years %d month and %d days old', BirthY,BirthM,BirthD);
elseif BirthM ~= 1
fprintf (fileID,'\n you are %d years %d months and %d days old', BirthY,BirthM,BirthD);
end
if BirthD == 1
fprintf (fileID,'\n you are %d years %d months and %d day old', BirthY,BirthM,BirthD);
elseif BirthD ~= 1
fprintf (fileID,'\n you are %d years %d months and %d days old', BirthY,BirthM,BirthD);
end
I'm not sure why but but displays two messages even when the conditions for the one of the if statements aren't met.

Answers (1)

Walter Roberson
Walter Roberson on 6 Oct 2020
Reformat your code:
if BirthM == 1
fprintf (fileID,'\n you are %d years %d month and %d days old', BirthY,BirthM,BirthD);
elseif BirthM ~= 1
fprintf (fileID,'\n you are %d years %d months and %d days old', BirthY,BirthM,BirthD);
end
if BirthD == 1
fprintf (fileID,'\n you are %d years %d months and %d day old', BirthY,BirthM,BirthD);
elseif BirthD ~= 1
fprintf (fileID,'\n you are %d years %d months and %d days old', BirthY,BirthM,BirthD);
end
Your conditions are not nested.
If you look at your if elseif sequence then the only times it will not output a string are the cases:
  • BirthM is nan
  • BirthM is vector (or matrix) including some 1 and some values that are not 1.

This question is closed.

Products


Release

R2019b

Community Treasure Hunt

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

Start Hunting!