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 comentarios

dpb
dpb el 12 de Feb. de 2020
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 el 13 de Feb. de 2020
Editada: Renato SL el 13 de Feb. de 2020
How about making a function (documentation here) instead?
With a function, you can declare every input in one line.

Iniciar sesión para comentar.

Respuestas (1)

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

Categorías

Productos

Preguntada:

el 12 de Feb. de 2020

Respondida:

el 17 de Feb. de 2020

Community Treasure Hunt

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

Start Hunting!

Translated by