what to do when there are same conditions in if and elseif

4 ビュー (過去 30 日間)
Roxanne Esguerra
Roxanne Esguerra 2020 年 7 月 2 日
編集済み: Roxanne Esguerra 2020 年 7 月 3 日
Here is my code,
if denominator==0
disp('Division by 0 is not possible.');
elseif numerator==0 && denominator==0
disp('The result is indeterminate.');
else
result = numerator/denominator;
fprintf('The result of the fraction is %.2f',result);
end
When the denominator is set to 0, it displays "Division by 0 is not possible."
When both the numerator and denominator are set to 0, it still displays "Division by 0 is not possible.". But it should be displaying: "The result is indeterminate.".
I think it's because of the same conditions in if and elseif that is denominator==0.
What should I do?
Thanks in advance!

採用された回答

Gaurav Aggarwal
Gaurav Aggarwal 2020 年 7 月 2 日
編集済み: Gaurav Aggarwal 2020 年 7 月 2 日
Hi Roxanne,
You are right. Since both the conditions have denominator == 0 common, if clause will become true and you get 'Division by 0 is not possible.'
For your application, you can re-order the if elseif clauses like following:
if numerator==0 && denominator==0
disp('The result is indeterminate.');
elseif denominator==0
disp('Division by 0 is not possible.');
else
result = numerator/denominator;
fprintf('The result of the fraction is %.2f',result);
end
Hope it helps. Thanks.
  1 件のコメント
Roxanne Esguerra
Roxanne Esguerra 2020 年 7 月 3 日
It worked! Thanks for the help!

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

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by