if statement not displaying

조회 수: 1 (최근 30일)
Jarren Berdal
Jarren Berdal 2020년 8월 7일
댓글: Walter Roberson 2020년 8월 8일
%%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에서 Model Predictive Control Toolbox에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by