if statement not displaying
1 回表示 (過去 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'
0 件のコメント
採用された回答
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 件のコメント
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 Center および File Exchange で Model Predictive Control Toolbox についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!