switch case & operators
9 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
dpb
le 22 Fév 2021
Modifié(e) : dpb
le 22 Fév 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...
Réponses (1)
Jan
le 22 Fév 2021
Modifié(e) : Jan
le 22 Fév 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
0 commentaires
Voir également
Catégories
En savoir plus sur Introduction to Installation and Licensing dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!