Respuesta aceptada

Torsten
Torsten el 14 de Jun. de 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 comentarios

Allen Wei
Allen Wei el 14 de Jun. de 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 el 14 de Jun. de 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 el 15 de Jun. de 2022
i see
thank you so much

Iniciar sesión para comentar.

Más respuestas (1)

Image Analyst
Image Analyst el 14 de Jun. de 2022

0 votos

Categorías

Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 14 de Jun. de 2022

Comentada:

el 15 de Jun. de 2022

Community Treasure Hunt

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

Start Hunting!

Translated by