if statement not displaying

6 次查看(过去 30 天)
%%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'

采纳的回答

Walter Roberson
Walter Roberson 2020-8-7
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 个评论
Jarren Berdal
Jarren Berdal 2020-8-8
now im getting 'Operands to the || and && operators must be convertible to logical scalar values.' error
Walter Roberson
Walter Roberson 2020-8-8
If you are using the any() like I show, then that error would only occur if your a had more than one dimension.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 RF Budget Analysis 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by