# Switch-case problem

조회 수: 21(최근 30일)
Tiffany McGinnis 12 Feb 2019
답변: OCDER 12 Feb 2019
inches = -2;
while ~(inches >=59 && inches <= 78)
inches = input('Enter the height in inches(59-78) : ');
end
pounds = 0;
while ~(pounds >= 90 && pounds <= 350)
pounds = input('Enter the weight in pounds(90-350) : ');
end
gender = 4;
while ~(gender >=1 && gender <=2)
gender = input('Is this person a female(1) or male(2)? Enter 1 or 2:');
end
%*****COMPUTE*****
% Compute conversions
meters = inches * 0.0254;
kilograms = pounds / 2.2046;
% Compute bmi
bmi= kilograms / ((meters)^2);
switch(gender)
case {'1'}
ibw = (45.5 + 2.3 * (inches - 60));
case {'2'}
ibw = (50.0 + 2.3 * (inches - 60));
end
% Convert IBW to pounds
ibw_in_pounds = ibw * 2.2046;
After running error message:
Undefined function or variable 'ibw'.
Error in assign04a (line 50)
ibw_in_pounds = ibw * 2.2046;

댓글을 달려면 로그인하십시오.

### 답변(1개)

OCDER 12 Feb 2019
ibw wasn't defined if gender is not '1' or '2', which are char. You want gender to be a double of value 1 or 2. Here's a fix.
switch gender
case 1
ibw = (45.5 + 2.3 * (inches - 60));
case 2
ibw = (50.0 + 2.3 * (inches - 60));
otherwise
ibw = %SPECIFY DEFAULT VALUE HERE
error('Incorrect gender option'); %OR, throw an error message
end

댓글을 달려면 로그인하십시오.

### Community Treasure Hunt

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

Start Hunting!

Translated by