Why is Q=30 after the loop is ran?
1 次查看(过去 30 天)
显示 更早的评论
B=1;
Q=0;
if B==1 && Q~=B
Q=20;
if B<0 || Q==20
Q=30;
end
elseif B<10
Q=40;
else
Q=50;
end
disp(Q)
%How do I trace the loop I thought Q would equal 20 after the first condition was met
0 个评论
采纳的回答
Les Beckham
2022-8-4
编辑:Les Beckham
2022-8-4
B=1;
Q=0;
if B==1 && Q~=B
Q=20;
if B<0 || Q==20 % you just set Q equal to 20 on the line above so this condition is true
Q=30;
end
elseif B<10
Q=40;
else
Q=50;
end
disp(Q)
Perhaps you meant to do this?
B=1;
Q=0;
if B==1 && Q~=B
Q=20;
elseif B<0 || Q==20
Q=30;
elseif B<10
Q=40;
else
Q=50;
end
disp(Q)
Issues like this are easier to find if you indent your code properly. In the Matlab editor, do Ctrl-A to select all of the code and then Ctrl-I to automatically indent it. Then you would have seen that that second if test was inside the first one.
3 个评论
Steven Lord
2022-8-4
Another useful technique to understand what the code is doing is to set a breakpoint on one of the lines of code (in this case I'd probably set it on the line immediately before the if statement.) When you run your code and MATLAB reaches the breakpoint, it will enter debug mode.
You can then step through the code line by line using the Step icon in the Run section of the Editor tab of the toolstrip, run multiple lines by using the Run to Here button (see the second section on this documentation page), or tell MATLAB to quit debugging.
If you run your original code step-by-step you'll see that it goes right from the line that starts the body of the first if statement directly to the second if statement. If you run the modified code provided by @Les Beckham it will skip directly over the elseif statements and the else statement.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!