BMI计算器如果语句被跳过

时间:2014-11-13 15:40:41

标签: c++ calculator

在我的

  

if statements

程序继续跳至"you are over weight"并显示在顶部而不是bmi旁边。

  

输出:http://i.imgur.com/1SF2cPc.png

此外,我的平均值似乎没有正确计算。

  

如何正确计算平均BMI?

#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;

int main()
{
    //declaring variables
    string name;
    int inches;
    double bmi, weight, noNames=0.0;
    double average_bmi;
    const double kilogram=0.45359237;
    const double metres = 0.0254;

    ofstream fout("bmi.dat");
    if (!fout.is_open())
    {
        cout << "error opening file ";
        system("pause");
        exit(-1);
    }
    fout << fixed << setprecision(2);

    fout << "Body Mass Index Report" << endl << endl;
    fout << left << setw(20) << "Name" << setw(20) << "Weight" << right << setw(10) << "Height" << setw(10) << "BMI"
        << setw(15) << endl << endl;

    cout << "Enter Your Name (crtl+Z to exit) ";
    getline(cin, name);
    while (!cin.eof())
    {
        cout << "Enter height in inches:";
        cin >> inches;
        while (cin.fail() || inches <=0)  //validate height for a number +'ve & >0
    {
        cin.clear();
        cin.ignore(80, '\n'); 
        cout << "Please enter a valid number ";
        cin >> inches;
    }
        cout << "Enter your weight (lbs): ";
        cin >> weight;
        cout << endl;

        while (cin.fail() || weight <= 0)
        {
            cin.clear();
            cin.ignore(80, '\n');
            cout << "Please enter a valid number  ";
            cin >> inches;
    }

        bmi = weight * kilogram / (inches * metres * inches * metres);

            cout << "Your Body Mass Index is  " << bmi;
        {   
            if (bmi > 18.5)
                fout << "  You are underweight.";
            else if ((bmi >= 18.5) && (bmi < 24.9))
                fout << "  You are normal weight.";
            else if (bmi < 25)
                fout << "  you are overweight." << endl << endl;
        }

        noNames++; //count number of names

        fout << left << setw(20) << name << setw(20) << weight << right << setw(10) << inches << setw(10)
            << bmi << setw(15) << endl;

        average_bmi = bmi++ / noNames++;
        fout << endl << endl << "Average bmi: " << average_bmi << endl;

        cout << ". Enter another name or ^Z to exit ";
        cin.ignore(80, '\n');
        getline(cin, name);
    }                

    if (noNames<0)
    {
        fout << "No values given " << endl;
    }
    cout << "program ended successfully" << endl;

    system("type bmi.dat");
    system("pause");
}

1 个答案:

答案 0 :(得分:1)

您已切换&#34;&lt;&#34;和&#34;&gt;&#34;比较BMI:

        if (bmi < 18.5)
            fout << "  You are underweight.";
        else if ((bmi >= 18.5) && (bmi < 24.9))
            fout << "  You are normal weight.";
        else if (bmi > 25)
            fout << "  you are overweight." << endl << endl;

顺便说一下,最后if是超级的。 else就足够了。