switch case & operators

9 visualizaciones (últimos 30 días)
Sela Uguy
Sela Uguy el 22 de Feb. de 2021
Editada: Jan el 22 de Feb. de 2021
if (pop==1)
w=str2double(get(handles.edit_kg,'string'));
h=str2double(get(handles.edit_cm,'string'));
body=1e4*(w)/(h^2);
set(handles.textbmi,'string',sprintf('%.2f',body));
switch (body)
case (body < 17)
s = 'Underweight';
case (body >=17) && (body < 23)
s = 'Normal';
case (body >= 23) && (body < 27)
s = 'Overweight';
otherwise
s = 'Obese';
end
set(handles.textstatus,'string',s);
handles.textstatus = s;
end
  2 comentarios
Sela Uguy
Sela Uguy el 22 de Feb. de 2021
I'm writing a BMI App, but the Obese kept printing. Why?
dpb
dpb el 22 de Feb. de 2021
Editada: dpb el 22 de Feb. de 2021
One would then conclude that the value of body is not numeric and under 27
>> body=1; switch (body)
case (body < 17)
s = 'Underweight';
case (body >=17) && (body < 23)
s = 'Normal';
case (body >= 23) && (body < 27)
s = 'Overweight';
otherwise
s = 'Obese';
end
>> s
s =
'Underweight'
>> body=nan;
>> switch (body)
case (body < 17)
s = 'Underweight';
case (body >=17) && (body < 23)
s = 'Normal';
case (body >= 23) && (body < 27)
s = 'Overweight';
otherwise
s = 'Obese';
end
>> s
s =
'Obese'
>>
shows the SWITCH block works; ergo the value going in must not be what you think.
Set a breakpoint at the line computing body to see what's going on and find logic errors...

Iniciar sesión para comentar.

Respuestas (1)

Jan
Jan el 22 de Feb. de 2021
Editada: Jan el 22 de Feb. de 2021
This is not the purpose of SWITCH/CASE. Please read the documentationm again:
doc switch
SWITCH evaluates its argument, ibn your case the variable body. Then it compares it with the expressions after the case statements. If body is e.g. 18, you get:
switch 18
case FALSE % This is the value of (body < 17)
...
case TRUE % Value of (body >=17) && (body < 23)
...
But 18 is neither TRUE nor FALSE.
You want an IF command instead of SWITCH.
if (body < 17)
s = 'Underweight';
elseif (body >=17) && (body < 23)
s = 'Normal';
elseif (body >= 23) && (body < 27)
s = 'Overweight';
else
s = 'Obese';
end
You can simplify this: After body<17 has been excluded already, there is no need to check for body >= 17 again. So htis is sufficient:
if (body < 17)
s = 'Underweight';
elseif (body < 23)
s = 'Normal';
elseif (body < 27)
s = 'Overweight';
else
s = 'Obese';
end

Categorías

Más información sobre Introduction to Installation and Licensing en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by