【问题标题】:How do I get BMI correct?我如何获得正确的 BMI?
【发布时间】:2020-05-05 05:41:14
【问题描述】:

我的 BMI 计算存在问题。请告诉我哪里出错了,因为答案总是以 -nan(ind) 的形式返回。我确定问题出在计算本身,因为我删除了 displayFitnessResults 函数并简化了代码,但仍然出现错误。

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

void getData(float weightP, float heightP)
{
    cout << "Enter indivual's wight in kilograms and height in metres: ";
    cin >> weightP >> heightP;
}

float calcBMI(float weightP, float heightP)
{
    return weightP / (heightP * heightP);
}

void displayFitnessResults(float calcBMI)
{
    if (calcBMI < 18.5)
    {
        cout << "The individuals BIM index is " << calcBMI << " and his/her weight status is underweight";
    }
    else if (calcBMI >= 18.5 && calcBMI <= 24.9)
    {
        cout << "The individuals BIM index is " << calcBMI << " and his/her weight status is healthy";
    }
    else if (calcBMI <= 25 && calcBMI >= 29.9)
    {
        cout << "The individuals BIM index is " << calcBMI << " and his/her weight status is overweight";
    }
    else (calcBMI >= 30);
    {
        cout << "The individuals BIM index is " << calcBMI << " and his/her weight status is obese";
    }
}


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

    cout.setf(ios::fixed);
    cout.precision(2);

    getData(weight, height);

    BMI = calcBMI(weight, height);

    displayFitnessResults(BMI);

    return 0;
}

【问题讨论】:

  • 除了 Remy 所说的,你应该更喜欢像这样声明你的变量 float weight, height, BMI; 原因是,如果你这样做了,那么编译器会警告你你正在使用 未初始化的变量,这会(希望)让您意识到getData 的问题。通过将变量初始化为无意义的值,您可以向编译器隐藏一个可能有用的警告。
  • calcBMI &lt;= 25 &amp;&amp; calcBMI &gt;= 29.9 永远不是true。是时候拿出那个调试器了。
  • 代码中的第一个错误。如果 calcBMI24.95 会发生什么? (提示:什么都没有打印出来)。 calcBMI==29.95 时存在类似的错误。
  • 代码审查:有一个函数以字符串形式返回status。那么你的显示功能就是:cout &lt;&lt; "The individuals BIM index is " &lt;&lt; calcBMI &lt;&lt; " and his/her weight status is " &lt;&lt; GetStatus(calcBMI);
  • @Bathsheba 谢谢,但这些是作业中给出的参数:1. 低于 18.5 体重不足 2. 18.5-24.9 健康 3. 25.0-29.9 超重 4. 30.0 及以上 肥胖跨度>

标签: c++ calculation


【解决方案1】:

您的getData() 函数采用其参数按值,因此它对它们所做的任何修改都不会反映回main() 中的变量,因此它们在传递给时仍然是0.0 calcBMI().

您需要通过引用传递参数

void getData(float &weightP, float &heightP)

【讨论】:

    猜你喜欢
    • 2019-09-03
    • 2012-07-21
    • 1970-01-01
    • 2021-12-25
    • 2014-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-29
    相关资源
    最近更新 更多