if statement not displaying
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
Jarren Berdal
il 7 Ago 2020
Commentato: Walter Roberson
il 8 Ago 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 Commenti
Risposta accettata
Walter Roberson
il 7 Ago 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 Commenti
Walter Roberson
il 8 Ago 2020
If you are using the any() like I show, then that error would only occur if your a had more than one dimension.
Più risposte (0)
Vedere anche
Categorie
Scopri di più su RF Budget Analysis in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!