C++BMI计算器问题

C++ BMI Calculator Problems

本文关键字:问题 计算器 C++BMI      更新时间:2023-10-16

我是一个初学者,所以请放松。我的问题在于我的输出。如果你输入一个全名,它就会崩溃。我应该用绳子以外的东西吗?它最初正确地显示输出,但随后也会向下运行,并添加超重线和额外的计算。如果计算结果加起来导致用户超重,它就能完美地工作。此外,未应用设置的精度。我被难住了。

int main()
{
    double height, weight, bmi; // height in inches, weight in pounds, bmi is total bmi of user
    string name; // name of the user
    int num; // the number 703 used for bmi calculation
    num = 703; // constant used for bmi calculation
    cout << "Please enter your full Name:"; // Asking the user to input their name
    cin >> name; // Users name 
    cout << "Please enter your height(in inches):"; // User height in inches
    cin >> height; // Users height
    cout << "Please enter your weight(in lbs):"; //Users weight in lbs
    cin >> weight; // Users weight
    bmi = (weight / pow(height, 2)) * num; // the actual calculation of the bmi of the user
    if (bmi >= 18.5 && bmi < 25) {
        cout << name << " your BMI is " << setprecision(1) << bmi; // outputting to the user their actaul BMI
        cout << endl;
        cout << "You are in the optimal weight category!"; // outputting their category
    }
    else if (bmi < 18.5) {
        cout << name << " your BMI is " << setprecision(1) << bmi;
        cout << endl;
        cout << "You are underweight.";
    }
    else (bmi >= 25); {
        cout << name << " your BMI is " << setprecision(1) << bmi;
        cout << endl;
        cout << "You are overweight.";
    }
    return 0;
}

这行有一个假的分号:

else (bmi >= 25); {

cin使用空白作为默认分隔符。因此,当您输入类似"First Last"的名称时,cin >> name;将只使用单词"First",而cin >> height;将尝试使用"Last",您将遇到错误。如果要允许使用全名,请尝试使用std::getline

当您使用>>输入字符串时,您只会得到一个单词的输入。用户全名的其余部分位于输入缓冲区中,直到下一个输入操作,例如,输入一个整数。然后该文本作为整数规范是无效的。

相反,使用getline来读取一行文本。


顺便说一句,为了获得关于例如用作语句的纯表达式的警告(这通常是错误的,代码中有一个例子),请提高编译器的警告级别。在Visual C++中使用/W4。对于g++,使用-Wall