Unit conversion using switch case or else if functions

Im supposed to use the switch case method or the else if method to solve this question. Anyone has any ideas on how to solve this?

5 件のコメント

dpb
dpb 2020 年 2 月 12 日
More important are your ideas...make a start and show us what you've done so far and then ask a specific question if/when you get stuck.
Renato SL
Renato SL 2020 年 2 月 12 日
I think the documentation for the if then else (here) and switch case (here) are clear enough with the given examples there.
Have you tried anything yet?
Melvinder Singh
Melvinder Singh 2020 年 2 月 12 日
I've managed to come up with this. Ignore the attempt at humor in the code. Is there any easier way to about doing this?
%%%%%%%%%%QUESTION 1%%%%%%%%%%%%
fprintf('Greetings Prof. Wean Sin,\n')
fprintf('Program will ask u to imput a value first followed by units.\n')
fprintf('Please enter units as L, m3, ft3 or gal.\n')
fprintf('Final value will be rounded off to the nearest 2 decimal places.\n')
L=input('Enter the amount of volume:\n');
x=input('Enter your current unit:\n','s');
z=input('Enter your desired unit:\n','s') ;
switch x %switching current unit and converting to L
case 'L'
L=L;
case 'm3'
L=L*1000;
case 'ft3'
L=L*28.3168;
case 'gal'
L=L*3.78541;
otherwise
fprintf('unit is invalid. sad face.\n');
end
switch z %now converting it to desired vol. unit
case 'L'
L=L;
case 'm3'
L=L/1000;
case 'ft3'
L=L/28.3168;
case 'gal'
L=L/3.78541;
otherwise
fprintf('unit is invalid. sad face.\n');
end
if L<0
fprintf('error, value is invalid. sad face\n');
else
fprintf('The volume is %.2f %s \n', L, z);
end
Melvinder Singh
Melvinder Singh 2020 年 2 月 12 日
Like to make it in such a way that I only need to input the starting value and unit together and not separately.
Renato SL
Renato SL 2020 年 2 月 13 日
編集済み: Renato SL 2020 年 2 月 13 日
How about making a function (documentation here) instead?
With a function, you can declare every input in one line.

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

回答 (1 件)

Srivardhan Gadila
Srivardhan Gadila 2020 年 2 月 17 日

0 投票

valuePlusUnit = "45.3245 ft3";
stringSplit = strsplit(valuePlusUnit);
value = str2num(stringSplit(1))
units = stringSplit(2)

カテゴリ

製品

質問済み:

2020 年 2 月 12 日

回答済み:

2020 年 2 月 17 日

Community Treasure Hunt

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

Start Hunting!

Translated by