a=0
t=1
while t==1
a=a+0.01
if a == 0.5
t=0
end
end
%why it only break loop when a=a+0.1

 Accepted Answer

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 Comments

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?
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.
i see
thank you so much

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

on 14 Jun 2022

Commented:

on 15 Jun 2022

Community Treasure Hunt

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

Start Hunting!