Akzeptierte Antwort

Torsten
Torsten am 14 Jun. 2022

0 Stimmen

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 Kommentare

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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Image Analyst
Image Analyst am 14 Jun. 2022

0 Stimmen

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange

Gefragt:

am 14 Jun. 2022

Kommentiert:

am 15 Jun. 2022

Community Treasure Hunt

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

Start Hunting!

Translated by