Réponse acceptée

Torsten
Torsten le 14 Juin 2022
a=0;
t=1;
while t==1
a=a+0.01;
if a >= 0.5
t=0;
end
end
a
a = 0.5000
t
t = 0
%why it only break loop when a=a+0.1

3 commentaires

Allen Wei
Allen Wei le 14 Juin 2022
i mean when i type a=a+0.1
t will become 0 and the loop breaks
but when a=a+0.01 loop can't break
is my matlab bugged or what happened?
Torsten
Torsten le 14 Juin 2022
a will not exactly become 0.5 because of floating point arithmetic. That's why statements as
if a == 0.5
are dangerous because they are almost never true.
Use
if a >= 0.5
to leave the while-loop as I did above.
Allen Wei
Allen Wei le 15 Juin 2022
i see
thank you so much

Connectez-vous pour commenter.

Plus de réponses (1)

Catégories

En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by