フィルターのクリア

Rewrite the script without using continue and break statement.

8 ビュー (過去 30 日間)
TEOH CHEE JIN
TEOH CHEE JIN 2022 年 2 月 14 日
コメント済み: Cris LaPierre 2022 年 2 月 14 日
I have written a code as below:
a=5:-1:-2;
i=1;
while(1)
if(a(i)<0)
break;
end
b=a(i)*2;
i=i+1;
if(b>=4)
continue;
end
disp('b<4')
end
disp('end of computation')
The script includes continue and break statements. Note that break will exit the innermost enclosing of while or for loop; while continue will jump to the end of the innermost enclosing while or for loop.
I wish to rewrite my code by removing break and continue so that it looks nicer. Any suggestions? Thank you.

採用された回答

Cris LaPierre
Cris LaPierre 2022 年 2 月 14 日
編集済み: Cris LaPierre 2022 年 2 月 14 日
You can remove the if statement containing the break by just using the opposte condition as the conditional statement controlling the while loop execution.
while a(i)>=0
You could reverse the contitional on your 2nd if statement, and replace continue with your disp command.
  1 件のコメント
Cris LaPierre
Cris LaPierre 2022 年 2 月 14 日
a=5:-1:-2;
i=1;
while a(i)>=0
b=a(i)*2;
i=i+1;
if(b<4)
disp('b<4')
end
end
b<4 b<4
disp('end of computation')
end of computation

サインインしてコメントする。

その他の回答 (1 件)

David Hill
David Hill 2022 年 2 月 14 日
Not sure what you are trying to do, but the final b is going to be zero.
a=5:-1:-2;
b=0;
disp('b<41');
disp('b<41');
disp('end of computation');

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by