Homework Help: What did I do wrong?

14 ビュー (過去 30 日間)
William Dowden
William Dowden 2021 年 3 月 2 日
コメント済み: Steven Lord 2021 年 3 月 2 日
My code works as intended, except when I input "kmpl", it displays the error shown below. What can I do to resolve this? Also, are there any simplifications I can make to my code? I feel like it can be optimized. Thanks!

回答 (1 件)

Jan
Jan 2021 年 3 月 2 日
編集済み: Jan 2021 年 3 月 2 日
The == operator compares its arguments elementwise. If they have a different number of elements, this fails, except it one is a scalar.
Solution: Compare char vectors with strcmp:
if strcmp(Units, 'mpg')
disp(x)
elseif strcmp(Units, 'kmpl')
disp(y)
end
If you post your code as text, the readers could post some improvements by copy&paste. The screenshot forces us to retype your code again.
Instead of creating x and y, it is more efficient to define only the string, which is used.
NUM2STR calls SPRINTF internally, so you can omit it, if it is an argument of SPRINTF.
Instead of creating a char which is used as input of DISP, you can write directly by FPRINTF:
if strcmp(Units, 'mpg')
fprintf('Your fuel economy is %g mile per gallon\n', mpg);
elseif strcmp(Units, 'kmpl')
fprintf('Your fuel economy is %g km per liter\n', kmpl);
end
  2 件のコメント
William Dowden
William Dowden 2021 年 3 月 2 日
Thank you very much! I appreciate you taking the time to answer my question! I hope you have a great day!
Steven Lord
Steven Lord 2021 年 3 月 2 日
Another approach, if you have a relatively small number of allowed options, would be switch and case.
a = {'apple', 'banana', 'cherry'};
for whichFruit = 1:numel(a)
f = a{whichFruit}
switch f
case 'apple'
disp('You gave me an apple!')
case 'cherry'
disp('You gave me a cherry!')
otherwise
disp('I don''t know what fruit you gave me!')
end
end
f = 'apple'
You gave me an apple!
f = 'banana'
I don't know what fruit you gave me!
f = 'cherry'
You gave me a cherry!

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

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by