2016-08-09 1 views
-2

私は友人が体重を減らすのを助けることに決めました。私はコーディングを知っていて、あなたのBMI(体質指数)を計算するプログラムを開発しようとしています。 ifステートメント。彼らは私がそれらを期待する方法を働いていない。ここに私がこれまでに持っていることがあり、それを見て、それがなぜ機能していないのか理解できません。私のifステートメントのデバッグ

#include <iostream> 
#include <cmath> 
using namespace std; 

int main() { 
    double weight; 
    double height; 
    double bmi; 
    cout << "Enter weight in kilograms:\n"; 
    cin >> weight; 
    cout << "Enter height in metres:\n"; 
    cin >> height; 

    bmi = weight/(pow(height,2)); 

    if (bmi < 18.5) { 
      cout <<"Your BMI is " << bmi <<", which means you are in the Underweight range" << endl; 
    } 
    else { 
    (bmi > 18.5) && (bmi < 24.9) 
      cout <<"Your BMI is " << bmi <<", which means you are in the Normal range" << endl; 
    } 

    else { 
     (bmi > 25.0) && (bmi < 29.9) 
      cout <<"Your BMI is " << bmi <<", which means you are in the Normal range" << endl; 
    } 

    else (bmi > 30) { 
      cout <<"Your BMI is " << bmi <<", which means you are in the Obese range" << endl; 
    } 
    return 0; 
} 

私は他に何度も使用できると言われましたが、それがエラーの原因かもしれないと私は考えています。

ありがとうございます。

+2

構文が間違っています:if(cond){if} else if(cond2){... } else if(cond3){...} else {....} ' – Garf365

+0

@ Garf365素晴らしいおかげで、私はそれを今すぐ行けます! –

+0

なぜ2つの「正常範囲」がありますか?違いは何ですか?他のものよりもう一つは「普通」ですか? –

答えて

2

正しい構文は次のとおりです。

if (bmi < 18.5) { 
     cout <<"Your BMI is " << bmi <<", which means you are in the Underweight range" << endl; 
} 
// else bmi >= 18.5, no need to test it again 
else if(bmi < 24.9) { 
     cout <<"Your BMI is " << bmi <<", which means you are in the Normal range" << endl; 
} 
else if(...) { 
    // ... 
} 
else { 
    // ... 
} 
+0

ちょっと言ってください:もしbmi == 18.5なら? – gnasher729

+0

いいえ:)私の答えを編集 – wasthishelpful

-2

あなたのif-else構文が間違っています。それは、(条件) - (もし他の条件) - そうすれば、このようになります:

bmi = weight/(pow(height,2)); 

if (bmi < 18.5) { 
     cout <<"Your BMI is " << bmi <<", which means you are in the Underweight range" << endl; 
} 
else if ((bmi > 18.5) && (bmi < 24.9)) 
     cout <<"Your BMI is " << bmi <<", which means you are in the Normal range" << endl; 
} 

else if ((bmi > 25.0) && (bmi < 29.9)) 
     cout <<"Your BMI is " << bmi <<", which means you are in the Normal range" << endl; 
} 

else /*(bmi > 30)*/ { 
     cout <<"Your BMI is " << bmi <<", which means you are in the Obese range" << endl; 
} 
return 0; 
+0

おっと、私がペーストしていたときにそれらの括弧を忘れていました。 –

+1

したがって、bmi = 18.5または25.0は肥満ですか? – gnasher729

+0

あなたの比較演算子と値が何をしているのか考えてみてください。例えばを確認する。 '<18.5 '、そして> 18.5は、正確な値、例えば、 '18.5'はあなたの明示的な条件ブロックのどれかによって捕らえられないので、誤って最後の' else'節に集中します。同様に、例えば24.9 <= n <= 25.0の値の「0.1」の範囲全体が一致しなくなり、そこで降格されることを意味します。比較対象の値を修正し、正しい演算子を使用して比較を行う必要があります。 –

関連する問題