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

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.
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?
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
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일
valuePlusUnit = "45.3245 ft3";
stringSplit = strsplit(valuePlusUnit);
value = str2num(stringSplit(1))
units = stringSplit(2)

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

제품

질문:

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