Can anybody help this loop question?

Temp = 20;
g = 0.1;
x = 0.11;
while(Temp > 0 && x ~= g)
Temp = Temp -1
x = x -0.001
if(x==g)
print('lalala')
end
end
Running code shown above should give me a 'lalala' message in commond window at 10th loop, but I didn't get it and also it didn't break the while loop when x==g;
I added a break point inside the loop and trying to run in step, I get results in the figure below and matlab judge that x==g is logic 0 while they should equal to each other.
Can somebody help explain it?
微信图片_20190221020958.png

 採用された回答

KSSV
KSSV 2019 年 2 月 21 日
編集済み: KSSV 2019 年 2 月 21 日

0 投票

Temp = 20;
g = 0.1;
x = 0.11;
while(Temp > 0 && x ~= g)
Temp = Temp -1
x = x -0.001
if abs(x-g)<=10^-3
disp('lalala')
end
end
Read about how to compare flottant numbers.

1 件のコメント

Stephen23
Stephen23 2019 年 2 月 21 日
編集済み: Stephen23 2019 年 2 月 21 日
Note: "flottant numbers" are known as floating point numbers in English:
They are known as "flottante" in French.

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

その他の回答 (0 件)

カテゴリ

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

タグ

質問済み:

2019 年 2 月 21 日

コメント済み:

2019 年 2 月 21 日

Community Treasure Hunt

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

Start Hunting!

Translated by