iT邦幫忙

2023 iThome 鐵人賽

0

C語言完整程式碼

#include <stdio.h>

int main() {
    float height, weight, BMI;
    int statusValid;

    while (1) {
        printf("請輸入身高(cm): ");
        statusValid = scanf("%f", &height);
        printf("請輸入體重(公斤): ");
        statusValid &= scanf("%f", &weight);

        if (statusValid != 1 || height <= 0 || weight <= 0) {
            printf("您輸入的身高或體重不正確\n");
            while(getchar() != '\n');  // 清空輸入緩衝區
            continue;
        }

        BMI = weight / ((height / 100) * (height / 100));
        
        char *status;
        if (BMI < 18.5) status = "過輕";
        else if (BMI < 24) status = "正常";
        else if (BMI < 27) status = "過重";
        else if (BMI < 30) status = "輕度肥胖";
        else if (BMI < 35) status = "中度肥胖";
        else status = "重度肥胖";

        printf("您的 BMI 為 %.0f, 屬於 %s\n", BMI, status);
        break;
    }

    return 0;
} 

輸出結果
https://ithelp.ithome.com.tw/upload/images/20240111/20160744IocNwxLbhb.png


也可以使用Pythontry except else function 改寫

Python完整程式碼

while True:
    try:
        height = float(input("請輸入身高(公分): "))
        weight = float(input("請輸入體重(公斤): "))
    except ValueError:
        print("這不是有效的數字")
        continue

    if height <= 0 or weight <= 0:
        print("您輸入的身高或體重不正確")
    else:
        BMI = weight / ((height / 100) ** 2)
        rounded_BMI = round(BMI, 0)

        if BMI < 18.5:
            status = "過輕"
        elif 18.5 <= BMI < 24:
            status = "正常"
        elif 24 <= BMI < 27:
            status = "過重"
        elif 27 <= BMI < 30:
            status = "輕度肥胖"
        elif 30 <= BMI < 35:
            status = "中度肥胖"
        else:
            status = "重度肥胖"

        print(f"您的BMI:{rounded_BMI}")
        print(f"您的BMI:{status}")
        break

參考資料:Python新手利用try except continue製作BMI計算機


上一篇
while迴圈應用與break脫離迴圈
下一篇
使用不同的控制符號來輸出不同型別的變數
系列文
C語言精讀研習46
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言