Info

Diese Frage ist geschlossen. Öffnen Sie sie erneut, um sie zu bearbeiten oder zu beantworten.

Why is my code displaying two messages instead of one?

3 Ansichten (letzte 30 Tage)
John Jamieson
John Jamieson am 6 Okt. 2020
Geschlossen: MATLAB Answer Bot am 20 Aug. 2021
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.

Antworten (1)

Walter Roberson
Walter Roberson am 6 Okt. 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.

Diese Frage ist geschlossen.

Produkte


Version

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by