如何在matlab中启用while 1循环



我计划进行BMI计算,在该计算中,只要两个输入都是正数,该程序就会提示用户重复输入新的输入。在这种情况下,我的输入是体重和身高。我在代码中应用了while循环。然而,当我输入两个正输入,并且在进行BMI计算后,该过程结束并退出。我可以知道我把哪一行编码错了吗?

while 1
if (Weight > 0 && Height > 0)
Weight = input('Please Enter Your Weight In kg: ');
Height = input('Please Enter Your Height In m : ');

BMI = Weight/(Height^2);
if (BMI<=18.5)
disp(['Health condition: THIN. Your BMI is ', num2str(BMI)]);

elseif (BMI>=18.6) && (BMI<=24.9)
disp(['Health condition: HEALTHY. Your BMI is ', num2str(BMI)]);

elseif (BMI<=25) && (BMI<=29.9)
disp(['Health condition: OVERWEIGHT. Your BMI is ', num2str(BMI)]);

else (BMI>=30)
disp(['Health condition: OBESE. Your BMI is ', num2str(BMI)]);

end

break
end
end

谢谢。

首先,如果尚未通过提示定义重量和高度条件,则不能调用if语句。所以你应该在if:之前调用input()

Weight = input('Please Enter Your Weight In kg: ');
Height = input('Please Enter Your Height In m : ');
if (Weight > 0 && Height > 0)

现在,您可以运行代码了。你的问题是break。这就是您定义代码的方式:

while loop 1 (forever)
prompt asking for weight and height
if weight & height > 0 (positive)
(...some other calculations and if)
break

如果你检查这个伪代码,你就告诉你的代码,如果权重和高度是正的,那么就打破while循环,因此它就停止了。正确的条件应该是:

if weight & height > 0 (positive)
run...
else (not positive)
break

这是你的代码修复:

while 1
Weight = input('Please Enter Your Weight In kg: ');
Height = input('Please Enter Your Height In m : ');
if (Weight > 0 && Height > 0)

BMI = Weight/(Height^2);

if (BMI<=18.5)
disp(['Health condition: THIN. Your BMI is ', num2str(BMI)]);


elseif (BMI>=18.6) && (BMI<=24.9)
disp(['Health condition: HEALTHY. Your BMI is ', num2str(BMI)]);


elseif (BMI<=25) && (BMI<=29.9)
disp(['Health condition: OVERWEIGHT. Your BMI is ', num2str(BMI)]);


else (BMI>=30)
disp(['Health condition: OBESE. Your BMI is ', num2str(BMI)]);

end

else
break
end
end

尽量总是注意身份。你的第一个if和最后一个end并不相等。

最新更新