Multiple conditions for while loop.

while (Ea0 >= 0.01)&&(Ea0 >= 0.01)||(Sr >= 10^-4)
This loop keeps on going even though the first part
(Ea0 >= 0.01)&&(Ea1 >= 0.01)
is met i.e. Ea0 and Ea1 dipped below 0.01, why is that?
I want it to stop if
(Ea0 >= 0.01)&&(Ea0 >= 0.01)
or
(Sr >= 10^-4)
are met! Thanks in advance!

回答 (1 件)

Joachim Schlosser
Joachim Schlosser 2016 年 4 月 18 日

2 投票

Error 1: You wrote Ea0 two times, but surely meant to write Ea1 in the second sub expression.
Error 2: Since the && is evaluated before '||, your loop will only end if both sides are false.
What you are describing above is another expression, where you want all sub expressions to hold true for the loop to continue:
while ((Ea0 >= 0.01) || (Ea1 >= 0.01)) && (Sr >= 10^-4)
Note the extra parens around the EaX expressions to specify that both must fail for the loop to end. If you want any sub expression to end the loop, replace '|| again by &&.

3 件のコメント

Stephen23
Stephen23 2016 年 4 月 18 日
Ahmad's "Answer" moved here:
thank u for ur reply but i'm confused! sorry I meant Ea1 yeah!
ur syntax work, although I don't understand it!
how is while ((Ea0 >= 0.01) vertical slash vertical slash (Ea1 >= 0.01)) && (Sr >= 10^-4) equal to (Ea0 >= 0.01)&&(Ea1 >= 0.01)" or "(Sr >= 10^-4) "
Joachim Schlosser
Joachim Schlosser 2016 年 4 月 18 日
:-) It is not, that's why it works.
The while loop does not take an expression describing the abortion prerequisites, but those for continuation. So effectively you have to turn your thoughts around and describe what has to be true to continue.
You may want to learn about Conjunctive Normal Form to understand how to move between the two thought models.
Shaarif Dilshad
Shaarif Dilshad 2021 年 1 月 13 日
if we write 2 times end then this is an error

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

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

質問済み:

2016 年 4 月 18 日

コメント済み:

2021 年 1 月 13 日

Community Treasure Hunt

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

Start Hunting!

Translated by