It is not giving me Results I don't know why?

1 回表示 (過去 30 日間)
shane watson
shane watson 2017 年 1 月 4 日
コメント済み: shane watson 2017 年 1 月 5 日
var1=2;
var2=3;
if var1==var2
disp('same');
if var1>var2
disp('var1 Greater var2');
elseif var1<var2
disp('var2 is greater var1');
end
end

採用された回答

Stephen23
Stephen23 2017 年 1 月 4 日
編集済み: Stephen23 2017 年 1 月 4 日
Because you have an if inside another if.
The problem is obvious if you format your code consistently. For example the default MATLAB indentation shows the problem clearly:
var1=2;
var2=3;
if var1==var2
disp('same');
if var1>var2
disp('var1 Greater var2');
elseif var1<var2
disp('var2 is greater var1');
end
end
See how the second if is inside the first if ? So if the first if condition is not true, then the second if will never be reached.
One solution is to use an elseif instead of the second if:
var1=2;
var2=3;
if var1<var2
disp('var2 is greater than var1');
elseif var1>var2
disp('var1 is greater than var2');
else
disp('same')
end
Summary: grumpy old professors telling you to format your code properly are not telling you this to annoy you. They are telling you this because consistent formatting makes it easier to spot mistakes!
  2 件のコメント
Image Analyst
Image Analyst 2017 年 1 月 4 日
Shane, in the MATLAB editor, type control-a (to select all) followed by control-i to properly indent your code.
shane watson
shane watson 2017 年 1 月 5 日
Thank you, Stephen Cobeldick

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

その他の回答 (0 件)

カテゴリ

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

タグ

タグが未入力です。

Community Treasure Hunt

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

Start Hunting!

Translated by