This simple code note working, HELP
1 回表示 (過去 30 日間)
古いコメントを表示
Poojitha Ariyathilaka
2020 年 6 月 13 日
コメント済み: Poojitha Ariyathilaka
2020 年 6 月 13 日
%this works well upto t==0.7, but not after 0.8
%give me an answer for this, not links
t=0;
for n=1:10
t=t+0.1;
disp(t)
if t==0.8
disp('if')
else
disp('else')
end
end
0 件のコメント
採用された回答
Ameer Hamza
2020 年 6 月 13 日
編集済み: Ameer Hamza
2020 年 6 月 13 日
Direct comparison using == of floating-point number does not give the correct result. You need to allow some level of tolerance. Try this
t=0;
for n=1:10
t=t+0.1;
disp(t);
if abs(t-0.8) < 1e-6
disp('if')
else
disp('else')
end
end
3 件のコメント
Ameer Hamza
2020 年 6 月 13 日
yes, that will work as well, but it is good to use the tolerance method. Otherwise, you will need to do rounding every time you do some mathematical operation on the variable.
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!