[英]How to enable while 1 loop in matlab?
我計划進行 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
並不相同。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.