if statement not displaying
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Jarren Berdal
le 7 Août 2020
Commenté : Walter Roberson
le 8 Août 2020
%%CODE FOR INGRIEDENTS CODE
disp('Ingrediants ID#');
disp('eggs: 10');
disp('avocado: 21');
disp('bread slices: 32');
disp('peanut butter: 43');
disp(' cup of spinich: 54');
disp('1/4 tbs of butter: 65');
disp('slices of cheese: 76');
n = input('how many ingredients do you have? ');
%%FOOD INPUT
for k = 1:n
a(k) = input(sprintf('Type code of Ingrediant #%d: ',k ));
A(k) = input(sprintf('Type quantity of Ingrediant #%d: ',k ));
end
if (n) >= (3)
elseif (a(k)) == (10)
elseif (a(k)) == (21)
elseif (a(k)) ==(32)
eggsandwich = ((a(1)*A(1))+(a(2)*A(2))+(a(3)*A(3)))
if eggsandwich >= (95)
disp('egg avocado sandwich')
end
end
is this case input is:
a(1) = 10;
A(1) = 1;
a(2)=21;
A(2)= 1;
a(3) = 32;
A(3) = 2;
eggsandwich = 95
trying to display 'egg avocado sandwich'
0 commentaires
Réponse acceptée
Walter Roberson
le 7 Août 2020
if (n) >= (3)
You are entering 3 ingredients, so n >= 3 is true, so the body of the "if" will be executed.
elseif (a(k)) == (10)
Tbe body of your "if" is empty. You will only go on to the "elseif" if the first "if" is false, but it is true. You can only get to the egggsandwich assignment statement if n >= 3 and a(k) == 10 and a(k) == 21 are all false, but a(k) == 32.
Note that the value of k is "left over" from the last value it was assigned in the for k = 1:n loop. You are not executing the if/elseif tree for every k value, only for the k that exists after the for k loop completely finishes, which in this case will be k == n.
I would suggest to you that you would be more interested in
any(a == 10) && any(a == 21) && any(a == 32)
2 commentaires
Walter Roberson
le 8 Août 2020
If you are using the any() like I show, then that error would only occur if your a had more than one dimension.
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Model Predictive Control Toolbox dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!