Nested if statements under for loop

1 回表示 (過去 30 日間)
Ernest Adamtey
Ernest Adamtey 2021 年 8 月 8 日
回答済み: Awais Saeed 2021 年 8 月 8 日
I have this nested if statements under a for loop. I want the for loop to calculate 3.1*5^2. And if the answer is 77.5, it should solve 3.1*3^2. Also if that equals 27.9. It should stop the for loop. But it seems to continue. Please help.
clc
A=['3' '.' '1' '*' '^' '2']
for n=0:length(A)
try
d=[A(1:n) '5' A(n+1:end)]
c=eval(d)
if c==77.5
e=[A(1:n) '3' A(n+1:end)]
j=eval(e)
if j==27.9
return
end
end
end
end
  1 件のコメント
Rik
Rik 2021 年 8 月 8 日
You should compare to a tolerance. (i.e. abs(value-target)<=tol;)
You should also remove those eval calls.

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

採用された回答

Awais Saeed
Awais Saeed 2021 年 8 月 8 日
eval(e) will never be equal to 27.9. To know the reason you have to set the output format from short(default) to long. After doing
format long
you will see that
eval(e) = 27.900000000000002
The workaround would be to remove unwanted numbers after decimal point and then compare. This is how I did it
clc
A=['3' '.' '1' '*' '^' '2']
for n=0:length(A)
try
d=[A(1:n) '5' A(n+1:end)]
c=eval(d)
if c==77.5
e=[A(1:n) '3' A(n+1:end)]
j=eval(e)
S = sprintf('%f',j); % convert it to string
[idx,~]=regexp(S,'[.]'); % search for decimal point
S(idx+2:end) = []; % delete everything from idx+2 till end
if isequal(S,'27.9') % compare S (modified eval(e)) with '27.9' char
return
end
end
end
end

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeWhos についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by