首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C 語言 BMI 計算程式:語法錯誤與邏輯bug全修正

     編輯:程式設計綜合問答

大一新手寫的 BMI 計算程式編譯報錯「expected '=', ',', ';', 'asm' or '__attribute__' before '{' token」且邏輯多處錯誤。

主要錯誤與修正

  1. 主函式缺少括號:int main → int main()。
  2. 變數名拼寫不一致:hieght / height、BIM / BMI 混用,統一修正。
  3. scanf 格式字串錯誤:%4.9lf 非標準,改用 %lf;逗號分隔需輸入逗號,建議改空白分隔 %lf %lf。
  4. 缺少 math.h 與 pow 連結:加 #include <math.h>,編譯加 -lm。
  5. 條件判斷邏輯錯誤:if(BIM ...) 應為 if (BMI < 18.5);最後一組 else (條件)? ... : ... 句法錯誤,改為 else if 鏈或 switch。
  6. printf 格式字串:%ls 為寬字串,普通字串用 %s;若要印出 BMI 值需加參數 printf("BMI=%.2f: ...", BMI);。

修正後可執行程式碼

#include <stdio.h>
#include <math.h>

int main() {
    double height, weight, BMI;
    printf("please enter your height(m) and weight(kg): ");
    scanf("%lf %lf", &height, &weight);
    BMI = weight / pow(height, 2);

    if (BMI < 18.5)
        printf("BMI=%.2f: you are too thin! eat more!\n", BMI);
    else if (BMI <= 24.99)
        printf("BMI=%.2f: congratulation! you are perfectly normal!\n", BMI);
    else if (BMI < 25)
        printf("BMI=%.2f: be careful, you are overweight now\n", BMI);
    else if (BMI < 28)
        printf("BMI=%.2f: you are too fat, watch out\n", BMI);
    else
        printf("BMI=%.2f: Warning: It is danger to be this FAT!\n", BMI);
    return 0;
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved